#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2024/05/24 09:28:10 +0900> """ Listbox上の各アイテムの背景色を変更しつつ、 アイテムをクリックすると別ウィジェットの背景色を変更するサンプル Windows10 x64 22H2 + Python 3.10.10 64bit + tkinter """ 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("", lambda e: root.destroy()) root.bind("", lambda e: root.destroy()) lbox.bind("<>", item_selected) root.mainloop()