Python Tk()按钮命令不完全工作



我对python编程很陌生,有一个基本的问题,我似乎无法解决自己-我希望有人能在这方面有所帮助!

我创建了一个.py文件,在用户和(随机)计算机之间运行一个基本的石头、剪子、布游戏。它通过tk()使用GUI,并且工作得非常好。

然后,我创建了另一个.py文件,这次是创建一个整体菜单GUI,从中我可以选择运行我的石头剪子布游戏。我可以创建这个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调试,但它似乎冻结在我身上!

我猜你是想在玩家选择特定游戏时保留主窗口。这意味着游戏应该在一个单独的框架中,最初是在一个单独的顶层关卡中。像下面这样修改rps文件,

from tkinter import *
from tkinter.ttk import *
import random
class RPS(Toplevel):
    def __init__(self, parent, title):
        Toplevel.__init__(parent)
        self.title(title)
    #game code goes in here, including other functions
# more code to define what this looks like
# including a Frame, buttons, labels, etc>
if __name__=='__main__':
    root=Tk()
    root.withdraw()
    RPS(title = "Rock, Paper, Scissors")
    root.mainloop()

这样,导入文件不会创建第二个根和主循环。

如果你想一次只运行一个游戏,你可以使用带有两个窗格的窗格窗口。Turtledemo就是这样做的。代码在turtledemo.main中。然后,您将从Frame中派生RPS并将其打包到第二个窗格中。

最新更新