当我一直按住 Ctrl+Up
时,我需要标签以 1000 毫秒的间隔更新。 (如果我按住 Ctrl+Up
5.2 秒,命令应该运行 5 次。)
after
方法似乎对此不起作用。它的行为也很奇怪,就好像它记录了我按下该键的次数,并且即使在松开 Ctrl+Up
后仍会继续循环。
from Tkinter import *
root = Tk()
def start(event):
global x
x = x+1
x_var.set(x)
root.after(1000, lambda: start(event))
x=1
x_var=IntVar()
x_var.set(x)
r = Label(root, textvariable=x_var)
r.pack()
root.bind('<Control-Up>', start)
root.mainloop()
最佳答案
这是一种在按住 Control + Up 的同时每 1000 毫秒运行一次命令的方法:
存储并更新current pressed statuses 控制和向上。
有一个
.after()
循环,每 1000 毫秒调用一次自身,在其中如果 Control 和 Up< 都运行所需的命令/kbd> 当前已按下。
代码
import Tkinter as tk
root = tk.Tk()
x = 1
x_var = tk.IntVar()
x_var.set(x)
r = tk.Label(root, textvariable=x_var)
r.pack()
isPressed = {"Control_L": False, "Up": False}
def update_key_status(key, value):
global isPressed
isPressed[key] = value
# Make the Press/Release events of both keys update the "isPressed" dictionary
for key in ["Up", "Control_L"]:
root.bind('<KeyPress-{}>'.format(key),
lambda evt, key=key: update_key_status(key, True))
root.bind('<KeyRelease-{}>'.format(key),
lambda evt, key=key: update_key_status(key, False))
def increment_x():
global x, x_var
x += 1
x_var.set(x)
def start():
if (isPressed["Control_L"] and isPressed["Up"]):
increment_x()
root.after(1000, start)
start()
root.mainloop()
关于python - 按住按钮和窗口更新问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689952/