Tkinter Button doesn´t change it´s relief after pressing it

时间秒杀一切 提交于 2021-01-28 10:02:27

问题


Why does my tkinter Button stays in the "sunken" relief after I press it?

import tkinter
from tkinter import messagebox as msgbox 

class GUI(object):
    def __init__(self):
        self.root = tkinter.Tk()
        self.root.geometry("200x200")
        self.root.title("Test")


        self.testButton = tkinter.Button(self.root, text="Click Me!")
        self.testButton.bind("<Button-1>", self.click)
        self.testButton.bind("<ButtonRelease-1>", self.release)
        self.testButton.pack()

    def release(self, event):
        event.widget.config(relief=tkinter.RAISED)

    def click(self, event):
        result =  msgbox.askokcancel("Continue?", "Do you want to continue?")
        if result:
            print("Okay")
        else:
            print("Well then . . .")
        print(event.widget.cget("relief"))
        print()

if __name__ == "__main__":
    test = GUI()
    test.root.mainloop()

The console shows that the relief is "raised" but on the GUI it stays in the "sunken" relief , why? The GUI after pressing the Button


回答1:


Your callback is printing "raised" because your code is run before the default button bindings, so the button relief is in fact raised at the point in time when your function is called.

I'm pretty sure this is what is causing the button to stay sunken:

  1. you click on the button, and a dialog appears. At this point the button is raised because tkinter's default binding has not yet had a chance to run 1, and it is the default bindings which cause the button to appear sunken
  2. a dialog appears, which steals the focus from the main window.
  3. you click and release the button to click on the dialog. Because the dialog has stolen the focus, this second release event is not passed to the button
  4. at this point the processing of the original click continues, with control going to the default tkinter binding for a button click.
  5. the default behavior causes the button to become sunken
  6. at this point, your mouse button is not pressed down, so naturally you can't release the button. Because you can't release the button, the window never sees a release event.
  7. Because the button never sees a button release event, the button stays sunken

1 For a description of how tkinter handles events, see this answer: https://stackoverflow.com/a/11542200/7432. The answer is focused on keyboard events, but the same mechanism applies to mouse buttons.



来源:https://stackoverflow.com/questions/43354019/tkinter-button-doesn%c2%b4t-change-it%c2%b4s-relief-after-pressing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!