[英]Changing background color by curselection() Tkinter
I'm facing an issue trying to change the background color by selecting it in the OptionMenu
. 我在尝试通过在OptionMenu
选择背景色来更改背景色时OptionMenu
。 The colors just don't change even if I add an else
clause. 即使添加else
子句,颜色也不会改变。
root=Tk()
root.geometry("200x200")
variative=IntVar()
list=[1,2,3,4]
variative.set('Select')
listbox=OptionMenu(root,variative,list[0],list[1],list[2],list[3])
def Background(event):
l=listbox.curselection()
if l==1:
root.config(bg='red')
elif l==2:
root.config(bg='yellow')
elif l==3:
root.config(bg='gray')
elif l==4:
root.config(bg='green')
listbox.bind('<<ListboxSelect>>',Background)
listbox.pack()
root.mainloop()
An OptionMenu
is not a Listbox
, that's why the <<ListboxSelect>>
event never happens. OptionMenu
不是Listbox
,这就是<<ListboxSelect>>
事件永远不会发生的原因。 However, you can pass a command option to the OptionMenu
when you create it. 但是,您可以在创建OptionMenu
时将命令选项传递给OptionMenu
。 This command will be called each time an option is selected in the menu and the selected option will be passed in argument. 每次在菜单中选择一个选项时,都会调用此命令,并且所选的选项将在参数中传递。
Here is an example: 这是一个例子:
from tkinter import Tk, OptionMenu, IntVar
root = Tk()
variative = IntVar()
option_list = [1,2,3,4]
variative.set('Select')
def background(sel):
if sel == 1:
root.config(bg='red')
elif sel == 2:
root.config(bg='yellow')
elif sel == 3:
root.config(bg='gray')
elif sel == 4:
root.config(bg='green')
listbox = OptionMenu(root,variative, *option_list, command=background)
listbox.pack()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.