我正在尝试制作一个 madlibs 应用程序,所以我在 Python 中为
input()
制作了一个 GUI,但是当我尝试这样做时,该函数没有运行,GUI 甚至没有出现!有人可以帮我吗?
这是我的代码:
import tkinter as tk
app=tk.Tk()
d=None
def check():
if d != None:
return
else:
app.after(10, check)
app.title("Vacation MadLibs")
def help():
helpWindow = tk.Toplevel(app)
tk.Label(helpWindow, text="How to play:\nThis game is called MadLibs!\nYou will be asked a series of questions that you will have\nto answer. After you are done answering the questions we\nwill show you a story that you created!").pack()
tk.Button(app,text="How to play",command= help).pack()
label=tk.Label(app,text="")
textbox=tk.Text(app, height= 1, width= 6 )
def enter():
global d
d = textbox.get("1.0","end")
button=tk.Button(app,command= enter)
def getInput(text):
label.pack()
textbox.pack()
button.pack()
check()
label["text"]=text
answer1= getInput("Name an emotion.... ")
answer2= getInput("Name a place.... ")
answer3= getInput("Name a person.... ")
answer4= getInput("Name a vehicle.... ")
answer5= getInput("Name a number.... ")
answer6= getInput("Name another number.... ")
answer7= getInput("Name a verb.... ")
answer8= getInput('Name an adjective.... ')
answer9= getInput("Name an animal... ")
answer10= getInput("Name another adjective.... ")
answer11= getInput("Name a food... ")
answer12= getInput("Name an emotion... ")
answer13= getInput("Name a famous person.... ")
answer14= getInput("Name an adjective.... ")
print("This is your story...")
print("Im so " + answer1)
print("Today we are going on a vacation to " + answer2)
print("Im going with " + answer3)
print("and we will travel there by " + answer4)
print ("The journey will take " + answer5 )
print ("hours and we will stay there for " + answer6)
print("days. After we arrived we decided to " + answer7)
print("Then we saw a " + answer8)
print(answer9)
print("We were starving so we decided to eat a " + answer10)
print(answer11)
print("We were so " + answer12)
print("Because we met " + answer13)
print("Overall the vacation was really " + answer14 )
我在网上看到,如果我使用 after 方法,我的应用程序不会崩溃,但它会崩溃。
这根本不是如何从用户那里获得输入。 GUI 开发的本质意味着程序总是在循环中运行以等待事件,因此您无需创建自己的循环。
相反,您可以使用 tkinter 的
wait_variable
方法等待变量设置。您可以在用户单击按钮或按下返回键时设置该变量。 wait_variable
与 mainloop
类似,只是它会在设置变量后立即自动返回。然而,像mainloop
一样,它会监听和响应事件。
它可能看起来像这样:
import tkinter as tk
def getInput(prompt):
label.configure(text=prompt)
textbox.delete("1.0", "end")
label.pack()
textbox.pack()
button.pack()
textbox.wait_variable(var)
return var.get()
def enter(event=None):
var.set(textbox.get("1.0", "end-1c"))
app=tk.Tk()
app.title("Vacation MadLibs")
var = tk.StringVar()
label=tk.Label(app,text="")
textbox=tk.Text(app, height= 1, width= 6 )
button=tk.Button(app,command= enter)
textbox.bind("<Return>", enter)
answer1= getInput("Name an emotion.... ")
answer2= getInput("Name a place.... ")
...