[英]I can't get a return from my Button - Python Tkinter
我对 Tkinter 很陌生,我正在尝试使用 command=function 从消息框中的按钮返回,但似乎什么也没发生:
import tkinter as tk
from tkinter import messagebox
def start_game(dif):
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():
return dif + 1
root.destroy()
def hard_difficulty():
return dif + 10
root.destroy()
easy_ask = tk.Button(root, text='Easy', command=easy_difficulty)
hard_ask = tk.Button(root, text='Hard', command=hard_difficulty)
mainLabel.pack()
easy_ask.pack(side=tk.LEFT)
hard_ask.pack(side=tk.LEFT)
root.mainloop()
difficulty = start_game(0)
print(difficulty)
这里的问题是没有地方可以返回dif+1
也没有dif+10
如果你需要的是那个值,1 或 10,我建议创建一个全局变量,我们称之为 Dif。
Dif = 0
在简单或困难难度 function 而不是return dif + 1 or 10
中,您需要通过以下方式调用变量:
global Dif
接着:
Dif = dif+1 # or 10 if its int the hard function
您不需要在easy_difficulty()
和hard_difficulty()
中返回值。 只需更新传递的参数dif
并在root.mainloop()
之后返回dif
。 但是,您需要在easy_difficulty()
和hard_difficulty()
中将dif
声明为非nonlocal
变量,否则它会被视为局部变量:
下面是修改后的代码:
import tkinter as tk
from tkinter import messagebox
def start_game(dif):
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():
nonlocal dif
dif += 1
root.destroy()
def hard_difficulty():
nonlocal dif
dif += 10
root.destroy()
easy_ask = tk.Button(root, text='Easy', command=easy_difficulty)
hard_ask = tk.Button(root, text='Hard', command=hard_difficulty)
mainLabel.pack()
easy_ask.pack(side=tk.LEFT)
hard_ask.pack(side=tk.LEFT)
root.mainloop()
else:
root.destroy()
# return the updated 'dif'
return dif
difficulty = start_game(0)
print(difficulty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.