目次
ラベルを作成する
ラベル (文字列や画像を表示するためのウィジェット) を作成するには、
tkinter.ttk モジュールの Label クラスを利用します。
Label オブジェクトを生成するときは、
「親ウィジェット」と「オプション」を指定することができます。
Example
source code
from tkinter import Tk
from tkinter import ttk
class MainFrame(ttk.Frame):
def __init__(self, master):
super().__init__(master)
self.pack()
self.make_style()
self.create_widgets()
def make_style(self):
pass
def create_widgets(self):
self.label1 = ttk.Label(self, text="Armadillo")
self.label1.pack()
root = Tk()
root.title("Tkinter win")
frame = MainFrame(root)
frame.mainloop()
result
オプションの設定
ラベル (ウィジェット全般) のオプションの設定方法は Python ドキュメントの「オプションの設定」 より、三通りあります。
オブジェクト生成時、キーワード引数を使用する
オブジェクト生成後、オプション名を辞書インデックスのように扱う
オブジェクト生成後に、config()メソッドを使って複数の属性を更新する
補足で、上記の config メソッドについて、
configure メソッドでも同様な動作をします。
text オプション
text オプションに文字列を指定すると、その文字列がラベルに表示されます。
Example では、オプションの設定に configure メソッドを使っていますが、
これは config メソッドと同様な動作をします。
Example
source code
from tkinter import Tk
from tkinter import ttk
class MainFrame(ttk.Frame):
def __init__(self, master):
super().__init__(master)
self.pack()
self.make_style()
self.create_widgets()
def make_style(self):
s = ttk.Style()
s.configure("TLabel", padding=8,
font=("", 10, "bold"),
background="#ffff00",
borderwidth=2,
relief="ridge")
def create_widgets(self):
self.label1 = ttk.Label(self, text="Armadillo")
self.label1.pack(side="top")
self.label2 = ttk.Label(self)
self.label2["text"] = "Bear"
self.label2.pack(side="top")
self.label3 = ttk.Label(self)
self.label3.configure(text="Cat")
self.label3.pack(side="top")
root = Tk()
root.title("Tkinter win")
frame = MainFrame(root)
frame.mainloop()