[英]Create windows in different functions in tkinter
我正在使用一個函數創建一個新窗口(例如Gui2 = Tk()
),然后需要在另一個函數中使用Gui2
,但尚未定義。
這是一款數學游戲,其主菜單有2個難度,即簡單和困難。 在主菜單之后,它會打開一個新窗口(這是在名為gui_setup
的函數中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()
首先,我想說的是,在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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.