python - tkinter 按钮,具有按下时间相关操作

标签 python user-interface button tkinter

我需要一些帮助来在 Tkinter 中创建一个代码,当按住特定按钮的时间更长时,该代码将输出不同的值。例如,如果按住按钮 a 1 秒,它将输出 1,或者按住 5 秒,它将输出 5,依此类推。


def set_down():
    acl.bind('<Button-1>',gn)
    brk.bind('<Button-1>',gn)


    # set function to be called when released
def set_up():
    acl.bind('<ButtonRelease-1>',fn)
    brk.bind('<ButtonRelease-1>',fn)


def fn(fn):
    print(0,'up')
def gn(gn):
    print(1,'down')

# the actual buttons: 

img = PhotoImage(file='round.gif')
brk_img = PhotoImage(file = 'red.gif')
acl = Button(GUI_CONTROL, text = 'accelerate', command = lambda:[set_down(), set_up()], image = img, padx = 4, pady = 4,
                bg = 'cyan', fg = 'cyan')
acl.place(relx = 0.7, rely = 0.5)

brk = Button(GUI_CONTROL, text = 'break', image = brk_img, command = lambda:[set_down(), set_up()],  padx=4,pady=4)

brk.place(relx = 0.7, rely=0.7)

所以我已经有了向用户输出是否被按下的功能,但现在我只需要它在按下时更改 fn() 和 gn() 的打印函数上的数值更长时间或更长。

最佳答案

您可以子类化tk.Button来创建一个TimePressedButton,它根据按下的持续时间执行操作:

import tkinter as tk
import time


class TimePressedButton(tk.Button):
    """A tkinter Button whose action depends on the
    duration it was pressed
    """

    def __init__(self, root):
        super().__init__(root)
        self.start, self.end = 0, 0
        self.set_down()
        self.set_up()
        self['text'] = 'press me'
        self['command'] = self._no_op

    def _no_op(self):
        """keep the tk.Button default pressed/not pressed behavior
        """
        pass

    def set_down(self):
        self.bind('<Button-1>', self.start_time)

    def set_up(self):
        self.bind('<ButtonRelease-1>', self.end_time)

    def start_time(self, e):
        self.start = time.time()

    def end_time(self, e):
        if self.start is not None:  # prevents a possible first click to take focus to generate an improbable time
            self.end = time.time()
            self.action()
        else:
            self.start = 0

    def action(self):
        """defines an action that varies with the duration
        the button was pressed
        """
        print(f'the button was pressed for {self.end - self.start} seconds')
        self.start, self.end = 0, 0


root = tk.Tk()
btn = TimePressedButton(root)
btn.pack()

root.mainloop()

关于python - tkinter 按钮,具有按下时间相关操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589084/

相关文章:

javascript - 按钮上的 ng-disabled,但当我更改值时它不会刷新

用于自定义类型的 python sqlite3 适配器

python - 通过 walrus := operator? 进行多次分配

python - 如何使用tensorflow函数tf.contrib.legacy_seq2seq.sequence_loss_by_example的 'weights'参数?

python - 为 QLineEdit 中输入的部分文本添加语法突出显示

Javascript:如何禁用提交按钮,直到验证所有字段?

python - 更改后强制 scapy 重新剖析图层

c++ - 脚本运行后引用 lua 表/对象

windows - SVN admin管理GUI工具

ios - 允许按钮在页面 View Controller 中触发新的 View Controller - swift