2024/05/24(金) [n年前の日記]
#1 [python] tkinterのListboxについて勉強中
Python + tkinter の Listbox について勉強中。各アイテム(項目)の背景色をそれぞれ変更して、クリックすると別ウィジェットの Label の背景色を変更する処理をしたい。
環境は Windows10 x64 22H2 + Python 3.10.10 64bit + tkinter。
以下のような感じになった。

_01_listbox.py
以下で実行。
少しだけ説明。Listbox() に渡すオプションについては以下。
メソッドについては以下。
環境は Windows10 x64 22H2 + Python 3.10.10 64bit + tkinter。
以下のような感じになった。

_01_listbox.py
import tkinter as tk
cols = [
(0, 0, 0),
(0, 0, 255),
(0, 255, 0),
(0, 255, 255),
(255, 0, 0),
(255, 0, 255),
(255, 255, 0),
(255, 255, 255),
]
def get_color_text(c):
return "#%02x%02x%02x" % (c[0], c[1], c[2])
def item_selected(e):
index = e.widget.curselection()
color = get_color_text(cols[index[0]])
lbl.config(bg=color)
lbox.configure(selectforeground="white", selectbackground=color)
# initialize tkinter
root = tk.Tk()
lbl = tk.Label(root, text="", width=20, height=5, borderwidth=1, relief=tk.SOLID)
lbl.pack(padx=8, pady=8)
lbox = tk.Listbox(
root,
selectmode=tk.SINGLE,
activestyle=tk.NONE,
font=("Arial", 16),
width=14,
bg="#666666",
)
lbox.pack(padx=8, pady=8)
for c in cols:
lbox.insert(tk.END, "%d, %d, %d" % (c[0], c[1], c[2]))
# set item color
for i, c in enumerate(cols):
lbox.itemconfig(i, bg=get_color_text(c))
root.bind("<Escape>", lambda e: root.destroy())
root.bind("<q>", lambda e: root.destroy())
lbox.bind("<<ListboxSelect>>", item_selected)
root.mainloop()
以下で実行。
python 01_listbox.py
少しだけ説明。Listbox() に渡すオプションについては以下。
- selectmode=tk.SINGLE ... 1つだけアイテムを選択できるようにする。
- activestyle=tk.NONE ... 選択時に文字表示スタイルを変更しない。
- font=("Arial", 16) ... フォント種類とフォントサイズの指定。
- width=14 ... 横幅。単位はおそらく文字数。
- bg="#666666" ... Listbox全体の背景色。
メソッドについては以下。
- アイテムの追加は、.insert(追加場所, 文字列) で行う。追加場所に tk.END を指定すれば、リストの最後にアイテムを追加できる。
- アイテムの背景色は、.itemconfig(インデックス値, bg="#ffffff") で指定できる。色の記述はHTMLと同様。
- .bind("<<ListboxSelect>>", 関数名) で、Listbox をクリックしてアイテムを選択した時に呼ばれる関数を指定できる。
- .curselection() で、選択されているアイテムのインデックス値を得られる。
[ ツッコむ ]
以上、1 日分です。