【问题标题】:How to make a momentary button in tkinter with Python 3.6如何使用 Python 3.6 在 tkinter 中制作瞬时按钮
【发布时间】:2018-07-24 12:57:38
【问题描述】:

我需要在 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()

【问题讨论】:

    标签: python tkinter python-3.6


    【解决方案1】:

    选项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()

    【讨论】:

    • 效果很好,谢谢。并感谢有关使用命令而不是绑定的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多