在 ms-window 应用程序上,我希望更新按钮样式“on-click”事件,并将其恢复为原始样式“on-release”。我至少测试了这两种方式,都没有效果:
BTN_TEXT_COLOR = '#b7babd'
BTN_BCKGD_COLOR = None # also tried with setting a color here
BTN_TEXT_COLOR_CLICKED = 'green'
BTN_BCKGD_COLOR_CLICKED = 'darkBlue'
BTN_NORMAL = (BTN_TEXT_COLOR, BTN_BCKGD_COLOR )
BTN_CLICKED = (BTN_TEXT_COLOR_CLICKED, BTN_BCKGD_COLOR_CLICKED )
# see Button class param: mouseover_colors
def run(self):
while True:
event, values = self.window.read()
if event in self.dispatch_dict:
self.visualClick(event) # <-- or: self.visualClick2(event)
func2call = self.dispatch_dict.get(event)
func2call(event)
else:
print(f"Event {event} NOT found in dispatch_dict")
if event in (None, 'Exit'):
break
if event == sg.WIN_CLOSED:
break
self.window.close()
exit(0)
def visualClick(self, evt):
self.window[evt].update(button_color=self.BTN_CLICKED) # NOK (colors changed at key up)
sleep(0.1)
self.window[evt].update(button_color=self.BTN_NORMAL) # NOK (or, keeps as 'pressed' if no-or-default original parameters)
def visualClick2(self, evt):
self.window[evt].mouseover_colors = self.BTN_CLICKED # NOK
sleep(0.1)
self.window[evt].update(button_color=self.BTN_NORMAL) # NOK
我还尝试在回调函数中更新窗口对象,和/或将
BTN_BCKGD_COLOR
设置为颜色而不是 None
:也没有效果。一般来说,事件是在释放按钮后产生的,所以来不及处理事件。
Button 元素存在默认绑定,因此绑定另一个元素后,它的工作方式会比您想象的更复杂。
bind(bind_string,key_modifier,propagate=True) 用于将 tkinter 事件添加到元素。 传播:如果为 True,则 tkinter 将被告知将事件传播到元素 传播:(布尔)
绑定时添加选项
propagate=False
,但Button的所有外观都需要自己处理。
示例代码
import PySimpleGUI as sg
font = ("Courier New", 16)
sg.theme("DarkBlue")
sg.set_options(font=font)
keys = ["Button 1", "Button 2"]
actions = {"PRESSED":("green", "darkblue"), "RELEASED":sg.theme_button_color()}
layout = [[sg.Button(key) for key in keys]]
window = sg.Window("Title", layout, finalize=True)
for key in keys:
window[key].bind('<ButtonPress-1>', '+PRESSED', propagate=False)
window[key].bind('<ButtonRelease-1>','+RELEASED', propagate=False)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event.endswith("+PRESSED") or event.endswith("+RELEASED"):
key, action = event.split("+")
window[key].update(button_color=actions[action])
window.close()