我遇到以下代码的问题:
def __init__(self):
window = Tkinter.Tk()
window.minsize(600,600)
window.maxsize(600,600)
window.title("test")
#window.iconbitmap('sample.ico')
menu_bar = Tkinter.Menu(window)
change_color_option = Tkinter.Menu(menu_bar, tearoff=0)
change_color_option.add_command(label = "Red", command = self.color_change(1, window))
change_color_option.add_command(label = "Blue", command = self.color_change(2, window))
change_color_option.add_command(label = "Yellow", command = self.color_change(3, window))
change_color_option.add_command(label = "Green", command = self.color_change(4, window))
change_color_option.add_command(label = "Purple", command = self.color_change(5, window))
change_color_option.add_command(label = "Brown", command = self.color_change(6, window))
file_menu_item = Tkinter.Menu(menu_bar, tearoff=0)
file_menu_item.add_command(label = "Quit", command = window.quit)
option_menu_item = Tkinter.Menu(menu_bar, tearoff=0)
option_menu_item.add_cascade(label = "change color", menu = change_color_option)
menu_bar.add_cascade(label="File", menu=file_menu_item)
menu_bar.add_cascade(label="Options", menu=option_menu_item)
window.config(menu=menu_bar)
window.mainloop()
def color_change(self, color, window):
if color == 1:
window.configure(background = "#CC0000")
elif color == 2:
window.configure(background = "#0000CC")
elif color == 3:
window.configure(background = "#FFFF00")
elif color == 4:
window.configure(background = "#336600")
elif color == 5:
window.configure(background = "#660099")
elif color == 6:
window.configure(background = "#663300")
然而我的问题是窗口将采用最后一种颜色(#663300),即使按下菜单按钮改变颜色也不会改变。我必须再次运行mainloop
,这不是我每次改变颜色时都想做的事情。有什么方法吗?
答案 0 :(得分:1)
要使用callback命令传递参数,您需要使用lambda
表达式。否则,Tkinter将在创建窗口小部件时执行回调,这就是它直接转到最后一个值的原因,因为这是流程流到达的最后一个值。
将lambda表达式格式化为:
change_color_option.add_command(label = "Red", command = lambda: self.color_change(1, window))