我是老师。我教数学,但是由于教育面临人力资源危机,我还有一些其他职责。我教孩子一些编程,他们做得很好。现在,我想和他们一起做一个蛇游戏,但是我在GUI应用程序中实现多线程时遇到了问题。
我发现了类似的情况,但没有解决方案。像这里:
使用键盘将字符移动迷宫
在这里:
tkinter.tk()和螺纹
def on_press(key):
print('{0} pressed'.format(key))
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
root = Tk()
root.mainloop()
我希望我希望窗口与听众同时运行。取而代之的是,我的代码会听到键盘,然后(在我向下拍摄后)弹出窗口。当我打电话给Mainloop后打电话时,它会逆转,然后首先出现窗口,然后将其击落后,听众开始工作。
I am a teacher. I teach math, but since education is facing human resources crisis, I have some additional duties. I teach kids a bit of programming, they do quite well. Now I'd like to make with them a snake game, but I have a problem achieving multithreading in my GUI app.
I found similar cases but no solutions. Like here:
Using the keyboard to move the character in a maze
and here:
Tkinter.Tk() and threading
def on_press(key):
print('{0} pressed'.format(key))
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
root = Tk()
root.mainloop()
I expected the window to run simultaneously with the listener. instead, my code listens to the keyboard and then (after I shoot the listener down) pops the window up. it reverses when I call the listener after calling the mainloop, then first the window appears and after I shoot it down the listener is starting to work.
发布评论
评论(2)
您不需要
侦听器
tkinter
。您可以使用root.bind
将函数分配给事件。您还可以
在tcl/tk文档中的每个键分隔键分配功能:
btw:
如果您想运行
tkinter
和pynput
同时您必须在join()
或
You don't need
Listener
intkinter
. You can useroot.bind
to assign function to events press and release.You can also assign function to every key separatelly
Keysyms in Tcl/Tk documentation: https://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm
BTW:
If you want to run
tkinter
andpynput
at the same time then you have to do it beforejoin()
or
侦听器
是一个线程,因此,如果您加入它,主线程将等到其结束直到继续处理。您只需在没有语句的情况下创建
侦听器
对象,它将沿主线程运行(直到回调函数将返回false
)Listener
is a thread, so if you join it your main thread will wait until its end to continue processing.You can just create a
Listener
object without thewith
statement and it will run along the main thread (until a callback function will returnFalse
)