[英]How to capture return value from tkinter buttons without using global variable?
[英]Return variable without global variables? Tkinter
我想把这个封闭在 function 中。 如果我将颜色设为全局变量,它会起作用,但否则不起作用。 有没有办法在没有全局变量的情况下完成这项工作?
import tkinter
def pick_color():
root = tkinter.Tk()
color = "blue"
def blue():
color = "blue"
root.destroy()
def red():
color = "red"
root.destroy()
b = tkinter.Button(root, text="blue", command = blue)
b.pack()
c = tkinter.Button(root, text="red", command= red)
c.pack()
root.mainloop()
return color
print(pick_color())
我想把这个封闭在 function
That's not how python works, variables are local to the function they are defined in, if you want to make a variable assessable to multiple function you got 2 options, either make it global, or use a class.
import tkinter
class color():
def __init__(self):
self.color = "blue"
self.root = tkinter.Tk()
def blue(self):
self.color = "blue"
self.root.destroy()
def red(self):
self.color = "red"
self.root.destroy()
def pick_color(self):
b = tkinter.Button(self.root, text="blue", command = self.blue)
b.pack()
c = tkinter.Button(self.root, text="red", command = self.red)
c.pack()
self.root.mainloop()
return self.color
choose = color()
print(choose.pick_color())
在这里,我定义了 class 颜色并将变量self.color
设置为 class 的本地变量,因此可以通过任何类方法访问它,例如blue()
和red()
。
使用您现在拥有的东西, red
和blue
正在创建自己的新变量,称为color
; 他们没有重新分配pick_color
的color
。 您需要告诉nonlocal
内部color
变量是 nonlocal :
def pick_color():
root = tkinter.Tk()
color = "blue"
def blue():
nonlocal color # color is "nonlocal" to blue
color = "blue"
root.destroy()
def red():
nonlocal color # And similarly, color is also nonlocal to red
color = "red"
root.destroy()
b = tkinter.Button(root, text="blue", command = blue)
b.pack()
c = tkinter.Button(root, text="red", command= red)
c.pack()
root.mainloop()
return color
如果没有 nonlocal , nonlocal
不知道您要引用现有的外部颜色,因为 Python 没有变量声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.