In the following code, I'm facing the problem that after I choose a text from the second menu then change the color in the first menu, the background changes but the label background doesn't change, how can I fix this?
For example, if I first choose "red" and "Hi" then choose "yellow", "Hi"'s background will still be red.
Thank you in advance!
from tkinter import *
from tkinter import ttk
def show_color(self):
def show_text(self):
txt = menu2.get()
if txt != "choose":
text.configure(text=txt, background=cur_color)
text.pack()
menu2.pack()
menu2.bind("<<ComboboxSelected>>", show_text)
cur_color = menu1.get()
if cur_color != "choose":
root.configure(bg=cur_color)
root = Tk()
root.geometry('900x500')
root.configure(bg='white')
root.resizable(False, False)
menu1 = ttk.Combobox(root, state="readonly", values=["choose", "red", "green", "yellow"], width=55)
menu1.current(0)
menu1.pack()
menu1.bind("<<ComboboxSelected>>", show_color)
menu2 = ttk.Combobox(root, state="readonly", values=["choose", "Hi", "Hello", "Hey"], width=55)
menu2.current(0)
text = Label(root)
root.mainloop()
CodePudding user response:
Since just changing color will not execute the nested function show_text()
and so the text background will not be updated.
To fix it, bind the two comboboxes to same function which update the text based on the selections of both the comboboxes:
from tkinter import *
from tkinter import ttk
def show_text(event):
cur_color = menu1.get()
if cur_color != "choose":
root.configure(bg=cur_color)
text.configure(bg=cur_color)
menu2.pack() # show the text selection combobox
txt = menu2.get()
if txt != "choose":
text.configure(text=txt)
text.pack()
root = Tk()
root.geometry('900x500')
root.configure(bg='white')
root.resizable(False, False)
menu1 = ttk.Combobox(root, state="readonly", values=["choose", "red", "green", "yellow"], width=55)
menu1.current(0)
menu1.pack()
menu1.bind("<<ComboboxSelected>>", show_text)
menu2 = ttk.Combobox(root, state="readonly", values=["choose", "Hi", "Hello", "Hey"], width=55)
menu2.current(0)
menu2.bind("<<ComboboxSelected>>", show_text)
text = Label(root)
root.mainloop()