2 回答

TA貢獻1794條經(jīng)驗 獲得超8個贊
沒有內(nèi)置的功能可以做到這一點,但是制作自己的Button可以很容易。您也走在正確的軌道上,唯一缺少的是需要使用它after來進行循環(huán)和after_cancel停止循環(huán):
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
class PaulButton(tk.Button):
"""
a new kind of Button that calls the command repeatedly while the Button is held
:command: the function to run
:timeout: the number of milliseconds between :command: calls
if timeout is not supplied, this Button runs the function once on the DOWN click,
unlike a normal Button, which runs on release
"""
def __init__(self, master=None, **kwargs):
self.command = kwargs.pop('command', None)
self.timeout = kwargs.pop('timeout', None)
tk.Button.__init__(self, master, **kwargs)
self.bind('<ButtonPress-1>', self.start)
self.bind('<ButtonRelease-1>', self.stop)
self.timer = ''
def start(self, event=None):
if self.command is not None:
self.command()
if self.timeout is not None:
self.timer = self.after(self.timeout, self.start)
def stop(self, event=None):
self.after_cancel(self.timer)
#demo code:
var=0
def func():
global var
var=var+1
print(var)
root = tk.Tk()
btn = PaulButton(root, command=func, timeout=100, text="Click and hold to repeat!")
btn.pack(fill=tk.X)
btn = PaulButton(root, command=func, text="Click to run once!")
btn.pack(fill=tk.X)
btn = tk.Button(root, command=func, text="Normal Button.")
btn.pack(fill=tk.X)
root.mainloop()
正如@ rioV8所提到的,該after()調(diào)用不是非常準(zhǔn)確。如果將超時設(shè)置為100毫秒,則通常可以在兩次調(diào)用之間等待100到103毫秒之間的任何時間。按住按鈕的時間越長,這些錯誤就會越多。如果要精確計時按鈕的按下時間,則需要使用其他方法。

TA貢獻1815條經(jīng)驗 獲得超6個贊
我認(rèn)為@Novel的答案應(yīng)該可以,但是這與您嘗試的內(nèi)容大致相同,不需要全新的課程:
from tkinter import *
INTERVAL=5 #miliseconds between runs
var=1
def run():
global running, var
if running:
var+=1
print(var)
window.after(INTERVAL, run)
def start_add(event):
global running
running = True
run()
def stop_add(event):
global running, var
print("Released")
running = False
window=Tk()
button = Button(window, text ="Hold")
button.grid(row=5,column=0)
button.bind('<ButtonPress-1>',start_add)
button.bind('<ButtonRelease-1>',stop_add)
mainloop()
添加回答
舉報