简体   繁体   English

如何在运行 tkinter 主循环的同时等待循环返回值?

[英]How do I wait for a loop to return a value while also running a tkinter mainloop?

I have created a window using tkinter and show that window using window.mainloop().我使用 tkinter 创建了一个窗口,并使用 window.mainloop() 显示该窗口。

window = Tk()
..
..
window.mainloop()

This tkinter window has a button that I waiting for the user to press:这个 tkinter 窗口有一个按钮,我等待用户按下:

button = Button(buttonFrame, text='Next', command=pressed)

However, I also have physical button in real life that the user can press.但是,我在现实生活中也有用户可以按下的物理按钮。 I have a function that communicates with the physical button over USB.我有一个通过 USB 与物理按钮通信的功能。 It just waits in a while loop for the physical button to be pressed and then returns true.它只是在 while 循环中等待物理按钮被按下,然后返回 true。 So if either the physical or digital button is pressed, the "pressed" function is called.因此,如果按下物理按钮或数字按钮,则会调用“按下”功能。

The problem is I don't know how to wait for both at the same time.问题是我不知道如何同时等待两者。 The code that waits for the USB response is blocking because it use a while loop.等待 USB 响应的代码是阻塞的,因为它使用了一个 while 循环。 The main loop of tkinter is also blocking. tkinter 的主循环也是阻塞的。 So how can I have both waiting at the same time?那么我怎样才能让两者同时等待呢?

I was able to get it working using the threading module:我能够使用线程模块让它工作:

window = Tk()
..
..
thread = threading.Thread(target=myButton)
thread.start()
window.mainloop()

Inside the myButton function, I call the function to get the button press from the USB button.在 myButton 函数中,我调用该函数以从 USB 按钮获取按钮按下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM