【发布时间】:2021-03-12 02:24:46
【问题描述】:
我正在尝试在按钮上切换activebackground 和activeforeground 的参数。但是,当尝试在选择按钮后更改背景颜色和文本字体并将这些设置重置为之前的状态时,如果单击任何其他按钮并且再次单击的按钮背景颜色和字体不会更改。
例如在上面的屏幕截图中,“对话历史记录”被选中,因此它是灰色加粗字体,所有其他菜单项都是普通字体。如果我点击“重要”,那么“重要”按钮就会变成灰色和粗体。渲染菜单的代码如下:
import tkinter as tk
root = tk.Tk()
def abc:
#this part is not running
def ResponsiveWidget(widget, *args, **kwargs):
bindings = {'<Enter>': {'state': 'active'},
'<Leave>': {'state': 'normal'}}
w = widget(*args, **kwargs)
for (k, v) in bindings.items():
w.bind(k, lambda e, kwarg=v: e.widget.config(**kwarg))
return w
button1 = ResponsiveWidget(
tk.Button,
root,
text='abc',
fg='black',
activebackground='#B7E3F9',
activeforeground='black',
highlightthickness=0,
relief='flat',
)
button1.place(x=0, y=50)
button2 = ResponsiveWidget(
tk.Button,
root,
text='xyz',
fg='black',
activebackground='#B7E3F9',
activeforeground='black',
highlightthickness=0,
relief='flat',command=lambda: abc
) #abc is not calling
button2.place(x=0, y=80)
root.mainloop()
新代码:
import tkinter as tk
root = tk.Tk()
selected_button = None
last_bg = None
def abc():
print("abc") #Not executing this part
def change_selected_button(button):
global selected_button, last_bg
if selected_button is not None:
selected_button.config(bg=last_bg)
selected_button = button
last_bg = button.cget("bg")
button.config(bg="orange")
def ResponsiveWidget(widget, *args, **kwargs):
bindings = {'<Enter>': {'state': 'active'},
'<Leave>': {'state': 'normal'}}
w = widget(*args, **kwargs)
for (k, v) in bindings.items():
w.bind(k, lambda e, kwarg=v: e.widget.config(**kwarg))
return w
button1 = ResponsiveWidget(
tk.Button,
root,
text='abc',
fg='black',
activebackground='#B7E3F9',
activeforeground='black',
highlightthickness=0,
relief='flat',
)
button1.place(x=0, y=50)
button1.config(command=lambda button=button1: change_selected_button(button))
button2 = ResponsiveWidget(
tk.Button,
root,
text='xyz',
fg='black',
activebackground='#B7E3F9',
activeforeground='black',
highlightthickness=0,
relief='flat',command=abc
)
button2.place(x=0, y=80)
button2.config(command=lambda button=button2: change_selected_button(button))
root.mainloop()
【问题讨论】: