gpt4 book ai didi

python - 具有时间按下依赖 Action 的 tkinter 按钮

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:31 26 4
gpt4 key购买 nike

我需要一些帮助来在 Tkinter 中创建一个代码,该代码将在按住特定按钮的时间更长时输出不同的值。因此,例如,如果按钮 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() 的打印函数上的数字值(如果它被按下)是否更长。

最佳答案

您可以子类化 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 - 具有时间按下依赖 Action 的 tkinter 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com