tkinter按钮,具有按下时间依赖的动作

时间:2019-06-13 22:01:04

标签: python user-interface button tkinter

我需要一些帮助来在Tkinter中创建代码,随着特定按钮的按下时间变长,该代码将输出differnet值。因此,例如,如果按住按钮a一秒钟,它将输出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()的数字值(如果按下)更长或更长时间。

1 个答案:

答案 0 :(得分:1)

您可以将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() 会根据按下的持续时间执行操作:

origin/master