(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

有关默认参数的更多详细信息。

您应该在bind方法中使用lambda匿名函数(类似于Buttoncommand参数(。

正确行:

questioner.bind('<Key-Return>', lambda x: greeting_user(name_input.get("1.0", "end-1c")))

相关内容

  • 没有找到相关文章

最新更新