我想创建一个tkinter GUI,它在按下按钮时给一个变量赋值,然后返回该值用于代码的其余部分:Python 3.4.2,使用Tkinter按钮返回一个变量供程序使用
from tkinter import *
def yes_command(ans):
ans = 'yes'
window.destroy()
return (ans)
def no_command(ans):
ans = 'no'
window.destroy()
return (ans)
window = Tk()
yes_no_label = Label(window, text="Yes or no?")
yes_no_label.grid(row=0, column=1)
YESbutton = Button(window, text="Yes", fg='green', command = lambda :yes_command(ans))
YESbutton.grid(row=1, column=0)
NObutton = Button(window, text = 'No', fg = 'red', command= lambda :no_command(ans))
NObutton.grid(row=1, column=2)
window.mainloop()
print(ans)
在此,GUI出现,一旦按下按钮,它就会关闭。然而,它不输出(因为这被称为函数的外部,我知道它将工作,如果它打印)。
什么进一步混淆我是,如果我是来取代回报(ANS)与打印(ANS)它将打印。这当然意味着它不会允许这个值离开函数吗?在这种情况下,为什么?
我会感谢任何帮助,所以提前致谢。
使用'command = ...'不会改变'ans'。你不是在变量中存储'yes_command(...)'和'no_command(...)',也不是'Tkinter.Button'。它*被*调用,但没有存储它返回的内容。 – zondo
由于调用函数的代码('mainloop()')忽略回调函数的返回值,所以不能从回调函数中返回某些东西。 –