我目前正在创建一个程序,它将不断检查按键,如果是 W 或 S,它将改变速度。但我遇到了 Tk 没有响应的问题?有谁帮忙欢呼一下。我的代码是:
import tkinter as tk #Importing the GUI Library
import time #Importing Time#
def onKeyPress(event): #Defining my function of keypress, and using GUI Library to get the keypress.
time.sleep(1) #Telling it to wait one second otherwise it will crash.
text.insert('end', 'You pressed %s\n' % (event.char, )) #Telling the user if he pressed the key or not.
speed = 50 #Setting the speed to 50 default
while speed > 0:
if event.char == 'w': #if key pressed = w:
speed = speed + 1 #Change speed by 1
time.sleep(1)
if event.char == 's':
speed = speed - 1
time.sleep(1)
print(speed)
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
最佳答案
您的主要问题是,当您按“s”以外的字母时,您将进入无限循环。当您按 's' 时,将需要 50 秒的时间退出循环,然后在按下下一个键时重新开始。此外,您的速度变量仅位于按键功能内,因此您无论如何都无法访问它,每次按下按键时您也会将其重置为 50
关于 tkinter,您需要了解的一些关键事项是应大力避免 time.sleep
并尝试让 while 循环在后台运行。
现在有几个选项可以做到这一点。您可以将该功能绑定(bind)到每个单独的键。
import tkinter as tk
def onKeyPress(event, value):
global speed # alter the global speed variable inside a function
# Keep in mind this insert will only occur for the selected keys
text.insert('end', 'You pressed %s\n' % (event.char, ))
speed += value # update speed variable with value
print(speed) # print current speed
speed = 50
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
# Individual key bindings
root.bind('<KeyPress-w>', lambda e: onKeyPress(e, 1)) # value is 1 for 'w'
root.bind('<KeyPress-s>', lambda e: onKeyPress(e, -1)) # value is -1 for 's'
root.mainloop()
或者像以前一样,您可以使用 if 语句来检查输入的字母。对于每个字母使用 if elif
而不是 if
是因为虽然它具有相同的效果,但 if block 将在条件为 True 时终止,否则它将遍历所有if 语句。
import tkinter as tk
def onKeyPress(event):
global speed # alter the global speed variable inside a function
text.insert('end', 'You pressed %s\n' % (event.char, ))
if event.char == 'w':
speed += 1
elif event.char == 's':
speed -= 1
print(speed) # print current speed
speed = 50
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
<小时/>
旁注:
目前,当我按下一个字母时,由于初始按键,它会插入 “sYou Pressed s”
。如果您在插入行之前添加此内容,那么它将删除键入的字符,并给出 “You Pressed s”
。
text.delete("%s-1c" % 'insert', 'insert')
关于Python - While 循环更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34921658/