>我正在尝试创建一个 tkinter GUI,它在按下按钮时为变量分配一个值,然后返回该值以在代码的其余部分使用:
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),它将打印。当然,这只是意味着它不允许值离开函数吗?在这种情况下,为什么?
我将不胜感激任何帮助,所以提前感谢。
对于您的问题,我有一个简单的解决方案。我使用全局 StringVar() 变量。您可以在任何函数中设置全局变量,并在以后打印。
from Tkinter import *
def yes_command():
global answer
answer.set('yes')
window.destroy()
def no_command():
global answer
answer.set('no')
window.destroy()
window = Tk()
yes_no_label = Label(window, text="Yes or no?")
yes_no_label.grid(row=0, column=1)
global answer
answer=StringVar()
YESbutton = Button(window, text="Yes", fg='green', command = lambda :yes_command())
YESbutton.grid(row=1, column=0)
NObutton = Button(window, text = 'No', fg = 'red', command= lambda :no_command())
NObutton.grid(row=1, column=2)
window.mainloop()
print(answer.get())
您可以创建一个类并从那里处理全局值。我还添加了一个名为 Test ans value
的新按钮,用于在每次按下Yes
或No
按钮时读取ans
的值。我还评论了.destroy()
行,以便您可以检查它是如何工作的。
from tkinter import *
class UI(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.ans = ''
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:self.yes_command())
YESbutton.grid(row=1, column=0)
NObutton = Button(window, text = 'No', fg = 'red', command= lambda:self.no_command())
NObutton.grid(row=1, column=2)
checkValue = Button(window, text = 'Test ans value', command= lambda:self.test_value())
checkValue.grid(row=2, column=1)
def yes_command(self):
self.ans = 'yes'
#window.destroy()
def no_command(self):
self.ans = 'no'
#window.destroy()
def test_value(self):
print self.ans
window = Tk()
newUI = UI(window)
window.mainloop()
谢谢大家的想法,我拿了一个简单的版本,然后通过调用它来测试它,将其添加到变量中,然后输出它以测试值是否重新分配:
from tkinter import *
def YNquestion():
global answer
def yes_command():
answer.set('yes')
window.destroy()
def no_command():
answer.set('no')
window.destroy()
window = Tk()
yes_no_label = Label(window, text="Yes or no?")
yes_no_label.grid(row=0, column=1)
answer=StringVar()
YESbutton = Button(window, text="Yes", fg='green', command = lambda :yes_command())
YESbutton.grid(row=1, column=0)
NObutton = Button(window, text = 'No', fg = 'red', command= lambda :no_command())
NObutton.grid(row=1, column=2)
window.mainloop()
YNquestion()
choice = answer.get()
print(choice)
YNquestion()
choice = answer.get()
print(choice)
如果我第一次按"是",第二次按"否",它会正确打印。在这个版本中,我删除了全局的不必要用法。它工作得很好,感谢所有的帮助!