英文:
Adding custom event handling loop to Tkinter
问题
这段代码目前运行正常,我只是在想长期运行是否会出现问题。
英文:
Is this an okay thing to do?
from tkinter import *;
from tkinter import ttk;
import keyboard;
root = Tk()
root.title("Feet to Meters")
################# custom event handling loop
while True:
keyboard.wait('space');
print('space was pressed! Waiting on it again...');
#################
root.mainloop()
The code runs fine so far I'm just wondering if I should expect troubles in the long run.
答案1
得分: 2
A while True
loop will block the main thread, meaning you can't do anything else while it is running which is not ideal. Instead, use root.bind
def callback(event):
print('space was pressed! Waiting on it again...')
root.bind('<space>', callback)
This will run callback
whenever you press space. event
is provided by Tkinter and contains more information about the keypress event.
Unlike your current method bind
will only work when the window has focus. If this is a problem, use threading instead.
import threading
def wait_space():
while True:
keyboard.wait('space');
print('space was pressed! Waiting on it again...')
threading.Thread(target = wait_space).start()
This will run the while True
loop in another thread, meaning the main thread can continue working.
英文:
A while True
loop will block the main thread, meaning you can't do anything else while it is running which is not ideal. Instead, use root.bind
def callback(event):
print('space was pressed! Waiting on it again...')
root.bind('<space>', callback)
This will run callback
whenever you press space. event
is provided by Tkinter and contains more information about the keypress event.
Unlike your current method bind
will only work when the window has focus. If this is a problem, use threading instead.
import threading
def wait_space():
while True:
keyboard.wait('space');
print('space was pressed! Waiting on it again...')
threading.Thread(target = wait_space).start()
This will run the while True
loop in another thread, meaning the main thread can continue working.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论