Tkinter:在函数内更改变量

1 投票
2 回答
1441 浏览
提问于 2025-04-15 11:55

我知道这种问题经常被问,但要么我找不到我需要的答案,要么就是找到的答案我看不懂。

我想做的事情是这样的:

spam = StringVar()
spam.set(aValue)
class MyScale(Scale):
    def __init__(self,var,*args,**kwargs):
        Scale.__init__(self,*args,**kwargs)
        self.bind("<ButtonRelease-1>",self.getValue)
        self.set(var.get())
    def getValue(self,event):
        ## spam gets changed to the new value set 
        ## by the user manipulating the scale
        var.set(self.get)
eggs = MyScale(spam,*args,**kwargs)
eggs.pack()

当然,我得到了“NameError: global name 'var' is not defined.”的错误。

我该怎么解决不能给getValue传递参数的问题呢?有人警告我不要使用全局变量,但这难道是我唯一的选择吗?难道我需要为每个想要改变的变量设置一个单独的scale类吗?我感觉我好像漏掉了什么很简单的东西...

编辑:
这就是你所说的吗?

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "C:\...\interface.py", line 70, in getValue
    var.set(self.get)
NameError: global name 'var' is not defined

抱歉,我才编程一个月,有些术语我还是不太懂。

2 个回答

1

我们来看看这个方法函数

    def getValue(self,event):
        ## spam gets changed to the new value set 
        ## by the user manipulating the scale
        var.set(self.get)

var.set(self.get) 这一行,有两个本地变量可以使用:

  • self
  • event

变量 var 并不是这个方法函数里的本地变量。可能它在类或脚本的其他地方被用过,但在这里并不算本地变量。

它有可能是全局变量,但这样做是不好的习惯。

我不明白你为什么会认为变量 var 在这个上下文中是可以被识别的。

2

请试试看这个。

很多示例代码都喜欢使用全局变量,比如你提到的“var”变量。

我用你的var参数来指向原来的spam对象,并在MyScale类中把它赋值给self.var_pointer。

下面的代码会在按键释放时改变'spam'(和'eggs')的值。

你可以通过输入eggs.get()或spam.get()来查看改变后的值。

from Tkinter import *
root = Tk()

aValue = "5"
spam = StringVar()
spam.set(aValue)

class MyScale(Scale):
    def __init__(self,var,*args,**kwargs):
        self.var_pointer = var
        Scale.__init__(self,*args,**kwargs)
        self.bind("<ButtonRelease-1>",self.getValue)
        self.set(var.get())
    def getValue(self,event):
        ## spam gets changed to the new value set 
        ## by the user manipulating the scale
        self.var_pointer.set(self.get())

eggs = MyScale(spam)
eggs.pack(anchor=CENTER)

撰写回答