2016-06-27 30 views
0

我对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调试,但它似乎冻结在我身上!

+1

一个问题是你正在创建两个根窗口(即:你调用'Tk()'两次)。 tkinter程序应该只有一个根窗口。 –

+0

请只在代码框中缩进代码一次,因此在格式化后它会显示为齐平,因此可以剪切并粘贴,并且可能在不进一步缩小的情况下运行。 –

回答

0

我认为你希望主窗口在选择特定游戏时保持不变。这意味着游戏应该在一个单独的框架中,最初在一个单独的Toplevel中。修改您的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并将其打包到第二个窗格中。