目标:我在列表框中选择一个选项。我想强调黄色选项。
问题:所有先前选择的选项也以黄色突出显示。我希望将最新的选择保留为黄色,列表框中的其他所有内容都保留为白色。
import tkinter as tk
root = tk.Tk()
fontfamily = tk.font.families()
def selectcolor(col=None):
fontlist.config(bg='white') ##<--PROBLEM CODE
option_selected = fontlist.curselection()
fontlist.itemconfig(option_selected[0], bg='yellow')
fontlist = tk.Listbox (root, bg='white')
fontlist.grid()
for eachfont in fontfamily:
fontlist.insert(tk.END, eachfont)
fontlist.bind('<<ListboxSelect>>', selectcolor)
##<<ListboxSelect>> is magic, this option is not shown in_
##ebook John Shipman tkinter 8.5 reference
##.curselection() doesn't work as expected
tk.mainloop()
答案 0 :(得分:0)
之前的项目保留黄色背景,因为您不会将其更改回来(这需要记住标记的最后一项)。但是使用selectbackground选项要容易得多。为了您的目的,以下是否有任何问题?
import tkinter as tk
root = tk.Tk()
box = tk.Listbox(selectforeground='black', selectbackground='yellow')
box.pack()
box.insert('end', 'one', 'two', 'three')
#root.mainloop()
答案 1 :(得分:0)
您可以对selectbackground
对象使用ListBox
选项。您不需要使用fontlist.config(bg='white')
行。解决方案就是这样:
import tkinter as tk
root = tk.Tk()
fontfamily = tk.font.families()
def selectcolor(col=None):
fontlist.config(bg='white') ##unnecessary
option_selected = fontlist.curselection()
fontlist.itemconfig(option_selected[0], selectbackground='yellow')
fontlist = tk.Listbox (root, bg='white')
fontlist.grid()
for eachfont in fontfamily:
fontlist.insert(tk.END, eachfont)
fontlist.bind('<<ListboxSelect>>', selectcolor)
##<<ListboxSelect>> is magic, this option is not shown in_
##ebook John Shipman tkinter 8.5 reference
##.curselection() doesn't work as expected
tk.mainloop()
由于问题,我编辑了代码。
import tkinter as tk
root = tk.Tk()
fontfamily = tk.font.families()
#you don't need to define a function to change highlight color.
fontlist = tk.Listbox (root, bg='white', selectbackground='yellow') #add selectbackground='yellow' here.
fontlist.grid()
for eachfont in fontfamily:
fontlist.insert(tk.END, eachfont)
#So it is necessary to bind a function now :)
tk.mainloop()