在 python tkinter 中按下按钮后无法覆盖按钮背景

Can't override background on Button after pressing it in python tkinter

我发现当指针悬停在 Button 上时使用 <Enter><Leave> 事件绑定来更改它的颜色时,在第一次单击按钮本身。

示例脚本:

from tkinter import Tk,Button

class App:
    def __init__(self):
        root=Tk()
        root.option_add('*Background','black')
        root.option_add('*Foreground','white')
        root.option_add('*Button.activeForeground','white')
        root.option_add('*Button.activeBackground','black')

        self.button=Button(root,text='Hello World')#,bg='black',fg='white')#,activebackground='white',activeforeground='black')
        self.button.pack(fill='both',expand=True,padx=10,pady=10)

        root.bind_class('Button','<Enter>',self.enter)
        root.bind_class('Button','<Leave>',self.leave)

        root.mainloop()
    def enter(self,event):
        print('entered')
        self.button.config(bg='red')
    def leave(self,event):
        print('left')
        self.button.config(bg='black')

if __name__=='__main__':
    App()

到目前为止我已经尝试过:

但这一切似乎都不起作用。当我在列表中做第一件事时,点击后按钮实际上什至没有变回给定的背景。

OS: Windows 10 Python: 3.7

提前致谢。

我可以用 bind_class 重现您的问题,但是我不知道为什么它在按下按钮后停止工作。我以前从未使用过bind_class

也就是说,直接在按钮上使用 bind 就可以了。

from tkinter import Tk, Button


class App:
    def __init__(self):
        root = Tk()
        root.option_add('*Background', 'black')
        root.option_add('*Foreground', 'white')
        root.option_add('*Button.activeForeground', 'white')
        root.option_add('*Button.activeBackground', 'black')

        self.button = Button(root, text='Hello World')
        self.button.pack(fill='both', expand=True, padx=10, pady=10)

        self.button.bind('<Enter>', self.enter)
        self.button.bind('<Leave>', self.leave)

        root.mainloop()

    def enter(self, event):
        print('entered')
        self.button.config(bg='red')

    def leave(self, event):
        print('left')
        self.button.config(bg='black')


if __name__ == '__main__':
    App()

就我个人而言,在构建这样的 class 时,我喜欢让 class 继承自 Tk() 而不是在 class.[=16= 中定义根目录]

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.option_add('*Background', 'black')
        self.option_add('*Foreground', 'white')
        self.option_add('*Button.activeForeground', 'white')
        self.option_add('*Button.activeBackground', 'black')

        self.button = tk.Button(self, text='Hello World')
        self.button.pack(fill='both', expand=True, padx=10, pady=10)

        self.button.bind('<Enter>', self.enter)
        self.button.bind('<Leave>', self.leave)

    def enter(self, event):
        print('entered')
        self.button.config(bg='red')

    def leave(self, event):
        print('left')
        self.button.config(bg='black')


if __name__ == '__main__':
    App().mainloop()