【问题标题】:Why am I not getting a return from my button - Message Box Python为什么我的按钮没有返回 - Message Box Python
【发布时间】:2020-07-06 18:48:11
【问题描述】:

对于我的游戏,我需要让用户选择一个难度来开始游戏,但我很难获得当运行下面的代码而不是从我的按钮获得正确的返回时,按钮消失并且我返回。这是我的代码:

def start_game():
    root = tk.Tk()
    root.attributes("-topmost", True)
    root.withdraw()
    answer = messagebox.askyesno("Welcome to Snake!", "Would you like to play?")
    if answer == True:
        root.deiconify()
        mainLabel = tk.Label(root, text='Choose a dificulty: ')

        def easy_difficulty():
            print('easy')
            return 1
        def medium_difficulty():
            print('medium')
            return 5
        def hard_difficulty():
            print('hard')
            return 10

        easy_ask = tk.Button(root, text='Easy', command=easy_difficulty())
        medium_ask = tk.Button(root, text='Medium', command=medium_difficulty())
        hard_ask = tk.Button(root, text='Hard', command=hard_difficulty())

        mainLabel.pack()
        easy_ask.pack(side=tk.LEFT)
        medium_ask.pack(side=tk.LEFT)
        hard_ask.pack(side=tk.LEFT)

    root.destroy()
    root.mainloop()

【问题讨论】:

  • 请提供minimal reproducible example。我不确定这是否是唯一的问题,但您可能不希望 command=easy_difficulty() 中的括号。

标签: python python-3.x button tkinter messagebox


【解决方案1】:

您不应该立即销毁您的根元素。 if 语句不是循环。您的代码继续运行,并且您的根元素被破坏。

删除root.destroy()

此外,当您在 tk 按钮中指定命令时,您不需要开始和结束括号。你只是这样做

easy_ask = tk.Button(root, text='Easy', command=easy_difficulty)

如果你想知道为什么,命令参数存储函数的内存地址,并在单击时运行它。如果你把括号放在那里,你已经运行了这个函数,在这种情况下返回None。当你点击按钮时,tk 会尝试运行None

【讨论】:

  • 我尝试了你所说的,它有效,但我仍然没有得到答案,但按下按钮时我仍然没有得到返回值。
  • @Vicdenz 您无法从单击按钮触发的回调中获取返回值。尝试将所需的值分配给全局变量。
  • @acw1668 是对的,我忘了说。我建议不要使用全局变量,而是在按钮触发的函数内运行必要的代码。好好规划你的代码。
猜你喜欢
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2022-10-15
  • 2012-09-07
相关资源
最近更新 更多