Adding custom event handling loop to Tkinter 添加自定义事件处理循环到Tkinter

huangapple go评论70阅读模式
英文:

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(&#39;space was pressed! Waiting on it again...&#39;)

root.bind(&#39;&lt;space&gt;&#39;, 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(&#39;space&#39;);
        print(&#39;space was pressed! Waiting on it again...&#39;)

threading.Thread(target = wait_space).start()

This will run the while True loop in another thread, meaning the main thread can continue working.

huangapple
  • 本文由 发表于 2023年5月6日 19:34:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188638.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定