简体   繁体   中英

Python Tkinter how to change background color while frame is active

i am having a problem with the following code:

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")

however my problem is that the window will take the last color (#663300) and it wont change even if i press the menu button to change color. I have to run mainloop again which is not something i want to do every time i change the color. Is there any way around it?

To pass an argument with the callback command, you need to use a lambda expression. Otherwise, Tkinter will perform the callback when the widget is made, which is why it's heading straight to the last value, as this is the last one the process flow reaches.

Format your lambda expressions like this:

    change_color_option.add_command(label = "Red", command = lambda: self.color_change(1, window))

More info: http://effbot.org/zone/tkinter-callbacks.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM