2014-04-12 38 views
0

我正在使用函數來創建一個新窗口(例如Gui2 = Tk()),然後我需要在另一個函數中使用Gui2,但它沒有定義。在tkinter中創建不同功能的窗口

這是一個數學遊戲, 有一個主菜單,有兩個困難,容易和困難。 在主菜單後打開一個新窗口(這是在一個名爲gui_setup的函數內完成的)。 請忘記其他錯誤,代碼是正在進行的工作。

我需要使根(Gui2)全球我猜? 但是,當我這樣做的程序不會打開窗口。

from tkinter import * 
import random as r 

n1 = 0 
n2 = 0 
answer = 0 
lives = 0 

def main_Gui_setup(): 
    mGui.title("Meh Maths Game") 
    mGui_label = Label(mGui,text="Please choose a diffiulty").pack() 
    mGui.geometry("240x160") 
    easy_button = Button(mGui,text="Easy",command=easy).pack() 
    hard_button = Button(mGui,text="hard",command=hard).pack() 

def Gui2_setup(x): 
Gui2 = Tk() #Here's the problem(I know it should be indented) 
    Gui2.title("Meh Maths Game") 
    Gui2_label = Label(text=("{0} Mode").format(x)) 
    Gui2.geometry("240x160") 
    mEntry = Entry(Gui2,textvariable=ment).pack() 
    mbutton = Button(Gui2, text = 'OK',command = handle_answer).pack() 

def easy(): 
    mGui.destroy() 
    Gui2_setup("Easy") 
    global lives 
    lives = 3 
    while lives > 0: 
     generate_question(0,100) 
     mlabel = Label(Gui2,text=("{0}+{1}=").format(n1,n2)).pack() 

def hard(): 
    mGui.destroy() 
    Gui2_setup("Hard") 
    global lives 
    lives = 1 
    while lives > 0: 
     generate_question(0,1000) 
     mlabel = Label(Gui2,text=("{0}+{1}=").format(n1,n2)).pack() 

def handle_answer(): 
    mtext = ment.get() 
    if int(mtext) == answer: 
     mlabel2 = Label(mGui,text='Correct').pack() 
    else: 
     mlabel3 = Label(mGui,text='Incorrect').pack() 
     global lives 
     lives = lives - 1 
    return 

def generate_question(y,z): 
    global n1 
    global n2 
    global answer 
    n1 = r.randint(y,z) 
    n2 = r.randint(y,z) 
    answer = int(n1+n2) 

mGui = Tk() 
main_Gui_setup() 
ment = StringVar() 
+1

您應該永遠不會有多個'Tk'的實例。如果你需要更多的窗口,創建'Toplevel'的實例 –

回答

0

首先我想說的是,在Tkinter中,您需要在代碼的末尾創建每個窗口,以便爲其添加mainloop()函數。杉木例如,

mGui = Tk() 

-----------在這裏寫下你的所有代碼--------------

mGui.mainloop() 

在你的問題,就在Gui2_setup年底加入這一行()函數

Gui2.mainloop() 

和最終的Gui2_setup()函數將這個樣子,

def Gui2_setup(x): 
    Gui2 = Tk() 
    Gui2.title("Meh Maths Game") 
    Gui2_label = Label(text=("{0} Mode").format(x)) 
    Gui2.geometry("240x160") 
    mEntry = Entry(Gui2,textvariable=ment).pack() 
    mbutton = Button(Gui2, text = 'OK',command = handle_answer).pack() 
    Gui2.mainloop()