将字符串更改为现有的变量名称,为多个变量创建 1 个函数(在 class 内,使用来自 Tkinter 的 root)
Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
from tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.plot = Canvas(master, width=500, height=120)
self.plot.pack()
self.1 = self.plot.create_text(10,10, text = "0")
self.2 = self.plot.create_text(30,10, text = "0")
self.3 = self.plot.create_text(50,10, text = "0")
def txt_change(self,name,value):
self.plot.itemconfigure(self.name, text=value)
所以在这里我只想创建 1 个函数,它可以通过包含一个名称来更改多个变量的值。然而,这个名字是一个字符串,但我希望 python 将该字符串解释为一个变量名。我有 20 个这样的变量,为每个变量创建一个新函数看起来不太干净。有没有聪明的方法来做到这一点?
我希望最后我可以使用这样的东西:txt_change("1",20)
这在python中称为setattr()
:
>>> a = App(...)
>>> setattr(a, "name", "foo")
>>> a.name
"foo"
使用 setattr()
在您的 class 中创建一个函数:
def update_property(self, name, value):
self.setattr(name, value)
这里,name
是class的peoperty
,value
是你要为前面设置的值属性
正确的解决方案不是将字符串转换为变量名。相反,将项目存储在列表或字典中。
例如,这使用字典:
class App:
def __init__(self, master):
...
self.items = {}
self.items[1] = self.plot.create_text(10,10, text = "0")
self.items[2] = self.plot.create_text(30,10, text = "0")
self.items[3] = self.plot.create_text(50,10, text = "0")
def txt_change(self,name,value):
item_id = self.items[name]
self.plot.itemconfigure(item_id, text=value)
...
app=App(...)
app.txt_change(2, "this is the new text")
from tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.plot = Canvas(master, width=500, height=120)
self.plot.pack()
self.1 = self.plot.create_text(10,10, text = "0")
self.2 = self.plot.create_text(30,10, text = "0")
self.3 = self.plot.create_text(50,10, text = "0")
def txt_change(self,name,value):
self.plot.itemconfigure(self.name, text=value)
所以在这里我只想创建 1 个函数,它可以通过包含一个名称来更改多个变量的值。然而,这个名字是一个字符串,但我希望 python 将该字符串解释为一个变量名。我有 20 个这样的变量,为每个变量创建一个新函数看起来不太干净。有没有聪明的方法来做到这一点?
我希望最后我可以使用这样的东西:txt_change("1",20)
这在python中称为setattr()
:
>>> a = App(...)
>>> setattr(a, "name", "foo")
>>> a.name
"foo"
使用 setattr()
在您的 class 中创建一个函数:
def update_property(self, name, value):
self.setattr(name, value)
这里,name
是class的peoperty
,value
是你要为前面设置的值属性
正确的解决方案不是将字符串转换为变量名。相反,将项目存储在列表或字典中。
例如,这使用字典:
class App:
def __init__(self, master):
...
self.items = {}
self.items[1] = self.plot.create_text(10,10, text = "0")
self.items[2] = self.plot.create_text(30,10, text = "0")
self.items[3] = self.plot.create_text(50,10, text = "0")
def txt_change(self,name,value):
item_id = self.items[name]
self.plot.itemconfigure(item_id, text=value)
...
app=App(...)
app.txt_change(2, "this is the new text")