简体   繁体   中英

Create windows in different functions in tkinter

I'm using a function to create a new window (eg. Gui2 = Tk() ) and then I need to use Gui2 in another function but it's not defined.

This is a Math game that has a main menu that has 2 difficulties, easy and hard. after the main menu it opens a new window(This is done inside a function called gui_setup ). Please forget any other errors, the code is a work in progress.

I need to make the root ( Gui2 ) global I guess? But when I do this the program doesn't open the window.

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()

First i want to say that in Tkinter, every window you create at the end of the code you need to add mainloop() function to it. Fir example,

mGui = Tk()

-----------Write your all code here--------------

mGui.mainloop()

In your problem, just add this line at the end of Gui2_setup() function

Gui2.mainloop()

And final your Gui2_setup() function will look like this,

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM