如何使用Python 3.6在tkinter中创建一个瞬时按钮

时间:2018-02-14 02:56:09

标签: python tkinter python-3.6

我需要在tkinter中有一个瞬时按钮,但是如果我使用<Button-1><ButtonPress-1>,那么在我发布之后,该函数似乎不会运行。例如,我有一个开始红色的按钮,当按下需要变绿时,当释放时它会变回红色。

这是我的代码:

from tkinter import *

class App:
    def __init__(self, master):
        self.on_offButton = Button(text="ON/OFF", font=('Helvetica', 20), bg='red')
        self.momentaryButton = Button(text="Momentary", font=('Helvetica', 20), bg='red')
        self.on_offButton.grid(row=0, column=0)
        self.momentaryButton.grid(row=1, column=0)
        self.on_offButton.bind('<Button-1>', self.on_offEvent)
        self.momentaryButton.bind('<ButtonPress-1>', self.momentaryPressedEvent)
        self.momentaryButton.bind('<ButtonRelease-1>', self.momentaryReleasedEvent)
    def on_offEvent(self, event):
        if self.on_offButton.cget('bg') == 'green':
            self.on_offButton.config(bg='red')
        elif self.on_offButton.cget('bg') == 'red':
            self.on_offButton.config(bg='green')
    def momentaryPressedEvent(self, event):
        if self.momentaryButton.cget('bg') == 'red':
            self.momentaryButton.config(bg='green')
        elif self.momentaryButton.cget('bg') == 'green':
            self.momentaryButton.config(bg='red')
    def momentaryReleasedEvent(self, event):
        if self.momentaryButton.cget('bg') == 'red':
            self.momentaryButton.config(bg='green')
        elif self.momentaryButton.cget('bg') == 'green':
            self.momentaryButton.config(bg='red')
root = Tk()
app = App(root)
root.mainloop()
root.destroy()

1 个答案:

答案 0 :(得分:0)

选项activebackground指定按下按钮时按钮的背景。按钮还有选项command来指定按下按钮时需要执行的操作,因此不需要绑定。这样,您的代码就完全符合:

from tkinter import *

class App:
    def __init__(self, master):
        self.on_offButton = Button(text="ON/OFF", font=('Helvetica', 20), bg='red', command=self.on_offEvent)
        self.momentaryButton = Button(text="Momentary", font=('Helvetica', 20), bg='red', activebackground='green')
        self.on_offButton.grid(row=0, column=0)
        self.momentaryButton.grid(row=1, column=0)
    def on_offEvent(self):
        if self.on_offButton.cget('bg') == 'green':
            self.on_offButton.config(bg='red')
        elif self.on_offButton.cget('bg') == 'red':
            self.on_offButton.config(bg='green')

root = Tk()
app = App(root)
root.mainloop()

注意:mainloop()会一直运行,直到用户销毁root,因此不需要root.destroy()