【发布时间】:2016-06-27 16:12:40
【问题描述】:
我对 python 编程很陌生,并且有一个我自己似乎无法解决的基本问题 - 我希望有人能够对此有所了解!
我创建了一个.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 程序应该只有一个根窗口。 -
请在写入框中仅缩进一次代码,以便格式化后显示为左对齐,因此可以剪切和粘贴,并且可以在不进一步取消缩进的情况下运行。
标签: python user-interface button tkinter