我正在创建一个游戏,供用户选择角色颜色并继续带领他们穿过迷宫。最初我让用户输入他们角色的名字和他们想要他们去的方向,但是改变了输入以使用带有 tkinter 的箭头键。现在我遇到了一个问题,因为 tkinter 为其输入打开了一个新窗口。
import view,datetime,Tkinter as tk
def main():
global root
if __name__ == "__main__":
view.root.update()
command = raw_input( "choose a player:" )
run1( command )
view.root.update()
while True:
root = tk.Tk()
print( "Press a key (Escape key to exit):" )
root.bind_all( '<Key>', key )
root.mainloop()
root.withdraw()
root.destroy()
view.root.destroy()
main()
这显示了我导入的内容和我的主要功能。
最佳答案
每次你这样做...
root = tk.Tk()
...
root.mainloop()
您正在创建一个全新的窗口。所以当然,当您在这个新窗口上使用 bind_all
时,那个新窗口就是接收输入的窗口。我真的不知道你想做什么,但很明显,这就是你看到你所看到的行为的原因。
大多数时候,您只需要一个root
——这就是它被称为“root”的原因!看起来你应该在 view.root
实例上使用 bind_all
,而不是在这个新根上。
此外,作为旁注,您的代码中的控制流真的很奇怪。为什么 if __name__ == '__main__'
在 main
函数中?通常这会在模块的顶层,并且会调用 main
本身。
关于python - 在 python 中使用 tkinter 时的新窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10475645/