python - (Tkinter)相同的代码 - 没有变化 - 当我运行它时会起作用然后不再起作用吗?绑定回车键功能
问题描述
这是我第一次看到这个,但我能够让它工作,然后在重新运行程序后,它不再工作了,然后它会,然后它不会再次,当我打开目的没有改变任何东西。
当我按下 ENTER 键时,有时会显示玩家的名字,但有时我会收到一条奇怪的消息,这让我相信它在用户输入他的名字之前从文本框获取数据。我究竟做错了什么?
# The program will start by explaining the rules, which are:
# The user will be asked random questions.
# For every right answer, a piece of the building will be built.
# 10 pieces will be necessary to finish it.
# if the user provides 3 wrong answers, the game will be over.
# The maximum number of questions will be 13.
from tkinter import *
import tkinter.simpledialog
import tkinter.messagebox
import random
questioner = Tk()
questioner.title(" -- Build the BUILDING! -- ")
# Explanation of rules and choice to begin or quit.
def begin():
rules_var = tkinter.messagebox.showinfo(" -- Build the BUILDING! -- ", """Game rules: You will be asked random questions, and
if you get more than 3 of them wrong, you will lose. If you are able to answer 10 questions correctly, you win!""")
building_game = tkinter.messagebox.askyesno(" -- Build the BUILDING -- !", "Do you want to start the game?")
if not building_game:
questioner.destroy()
else:
second_stage()
# Entering name.
def second_stage():
name_label = Label(questioner, text="What's your name?", font=('arial', 30, 'bold')).pack()
name_input = Text(questioner, width=30, height=1, font=('courier', 18))
name_input.pack()
submit_button = Button(questioner, text="Submit", command=lambda: greeting_user(name_input.get("1.0", "end-1c"))).pack()
questioner.bind('<Key-Return>', greeting_user)
# Being welcomed.
def greeting_user(name):
welcome_msg = f"Hi {name}, the game will start in 5 seconds."
welcome_length = 5000
top = Toplevel()
top.title('Welcome!')
Message(top, text=welcome_msg, font=20, padx=50, pady=40).pack()
top.after(welcome_length, top.destroy)
# greeting = Label(questioner, text="Hi " + str(name) + "! The game will start in 5 seconds.")
# greeting.pack()
# greeting = tkinter.messagebox.showinfo(f"Get ready!", f"Hi {name}, the game will start in 5 seconds.")
# time.sleep(3)
# questioner.destroy()
begin()
questioner.mainloop()
解决方案
您可以使用 传递名称,以与lambda
在命令中使用它的方式相同的方式使用它,但不要忘记传递默认参数。:
def second_stage():
name_label = Label(questioner, text="What's your name?", font=('arial', 30, 'bold')).pack()
name_input = Text(questioner, width=30, height=1, font=('courier', 18))
name_input.pack()
submit_button = Button(questioner, text="Submit", command=lambda: greeting_user(name_input.get("1.0", "end-1c"))).pack()
questioner.bind('<Key-Return>', lambda e: greeting_user(name_input.get("1.0", "end-1c"))) # e is the default argument