Labelとは
文字と画像を表示するウェジットです。Labelの背景色を指定できます。文字の描画ではフォントを指定できできます。また、文字色も指定できます。
# -*- coding: utf-8 -*-
import tkinter as tk
def main():
root = tk.Tk()
root.title("Frame App")
root.geometry("400x300")
frame1 = tk.Frame(root, width= 150, height=200,
bg='#88ff88',
borderwidth=0, relief='flat')
frame1.place(x=0, y=0)
img = tk.PhotoImage(file='satellite.png')
label1 = tk.Label(
frame1,
bg='yellow',#背景色
foreground = 'red',#文字色
wraplength = 75,#文字の折り返し ピクセルで指定
justify = 'left',#空白部分があるときの文字の表示開始位置
font = ("VL ゴシック", 10, "bold"),#フォントの指定
text='Hello12345678901234567890',
image=img,
compound=tk.TOP#画像を上に配置
)
label1.place(x=0, y=0)
root.mainloop()
if __name__ == "__main__":
main()
文字の最後の0が左寄せになっています。 justify = 'left',#空白部分があるときの文字の表示開始位置 justifyはleft,center,rightから選択できます。
時刻をLavelに表示
Labelを使った時計です。
リアルタイムに時刻を表示するためにはタイマーが必要です。signalを使いました。しかし、安定に動作しません。何か別な方法があるか調べてみると、afterというのがありました。これは正確なタイマーではないようですが、サンプルプログラムには十分です。
# -*- coding: utf-8 -*-
import tkinter as tk
import time
g_root = None
g_label = None
def unitTimer():
global g_root, g_label
now = time.strftime("%H:%M:%S")
g_label.configure(text = now)
g_root.after(500, unitTimer)
def main():
global g_root, g_label
g_root = tk.Tk()
g_root.title("時計")
g_root.geometry("240x80")
g_root.after(500, unitTimer)
g_label = tk.Label(
g_root,
font = ("VL ゴシック", 32, "bold"),#フォントの指定
bg='yellow', relief=tk.RIDGE, bd=10)
g_label.grid()
g_root.mainloop()
if __name__ == "__main__":
main()
rootとlabelをグローバル変数にしてmain()とann()からアクセスできるようにします。: g_root.after(500, unitTimer)
afterの引数 500:500ミリ秒 unitTimer:コールバック関数 unitTimer()内で g_label.configure(text = now)
ラベルに時刻を設定しています。 案外簡単に時計ができました。s |