我对Python编程还很陌生,有一个很基本的问题,我似乎无法解决我自己 - 我希望有人能够阐明这一点!Python Tk()按钮命令不能完全工作
我创建了一个.py
文件,该文件在用户和(随机)计算机之间运行基本的Rock,Paper,Scissors游戏。这通过tk()
使用GUI,并且工作得很好。
然后,我创建了另一个.py
文件,这次创建一个整体菜单GUI,从中我可以选择运行我的Rock,Paper,Scissors游戏。我可以创建这tk()
罚款,按钮来选择RPS游戏,游戏加载,但这次它根本不工作!我可以按下按钮,但他们不会推进游戏。
这里是我的game.py
代码:
from tkinter import *
from tkinter.ttk import *
import random
def gui():
<game code goes in here, including other functions>
root=Tk()
root.title("Rock, Paper, Scissors")
# more code to define what this looks like
# including a Frame, buttons, labels, etc>
if __name__=='__main__':
gui()
然后,我创建了整体游戏菜单,menu.py:
from tkinter import *
from tkinter.ttk import *
import random
import game
main=Tk()
main.title("J's games")
mainframe=Frame(main,height=200,width=500)
mainframe.pack_propagate(0)
mainframe.pack(padx=5,pady=5)
intro=Label(mainframe,
text="""Welcome to J's Games. Please make your (RPS) choice.""")
intro.pack(side=TOP)
rps_button=Button(mainframe, text="Rock,Paper,Scissors", command=game.gui)
rps_button.pack()
test_button=Button(mainframe,text="Test Button")
test_button.pack()
exit_button=Button(mainframe,text="Quit", command=main.destroy)
exit_button.pack(side=BOTTOM)
main.mainloop()
如果任何人都可以看到一些明显的,请让我知道。我很困惑它为什么独立运作,但不是当我将它合并到另一个函数(按钮命令)时。我试过了IDLE调试,但它似乎冻结在我身上!
一个问题是你正在创建两个根窗口(即:你调用'Tk()'两次)。 tkinter程序应该只有一个根窗口。 –
请只在代码框中缩进代码一次,因此在格式化后它会显示为齐平,因此可以剪切并粘贴,并且可能在不进一步缩小的情况下运行。 –