如何将一个类变量传递给另一个类



我正在制作一个条形码生成器。我需要类GUI中的输入由类Barcode读取,这样它就可以在画布上打印线条。

from tkinter import *
class GUI(Frame):
def __init__(self, master=None):
...
self.code_input = Entry(master)
self.code_input.pack()
self.code = self.code_input.get()
...
self.barcode = Barcode(master, height=250, width=200)
self.barcode.pack()
self.barcode.draw()
....
class Barcode(Canvas):
def draw(self):
self.ean = GUI.code

如果我像上面一样直接引用,它会说AttributeError: type object 'GUI' has no attribute 'code'

如果我做继承方法(基于https://stackoverflow.com/a/19993844/10618936),class Barcode(Canvas, GUI)它说的与以前的相同

如果我使用setter和getter方法:

class GUI(Frame)
def __init__(self, master=None):
...
@property
def code(self):
return self.__code
@code.setter
def code(self, code):
self.__code = code

然后self.ean = GUI.code,它不会运行程序并说TypeError: 'property' object is not subscriptable代替

我该如何解决这个问题?我的程序结构真的不好吗?我真的一点都不擅长编程。。。我只想把GUI中的变量转移到类Barcode中,这样它就可以计算并将结果返回到GUI以显示条形码

您需要创建一个GUI的实例,否则您只是在引用未定义code的静态类。你可以像这个例子一样访问它

class A():
def __init__(self):
self.code = "A"
class B():
def __init__(self):
self.code = "B"
def foo(self):
print(self.code + A().code)
b = B()
b.foo() # Outputs "BA"

否则,要像访问类中的静态变量一样访问它,您需要在类根级别中定义它

class A():
code = "C"
def __init__(self):
self.code = "A"
class B():
def __init__(self):
self.code = "B"
def foo(self):
print(self.code + A.code)
b = B()
b.foo() # Outputs "BC"

您应该将GUI对象传递给Barcode类,在创建Barcode实例时该类为self。如果您希望Barcode位于GUI帧内,也可以直接将其用作Canvas主机
另一件需要注意的事情是,按照您现在的方式,self.code将是并且仍然是一个空字符串,因为您只有在创建Entry小部件之后才定义它,此时它是空的。当您想对此时的内容执行某些操作时,应该在条目上使用get

from tkinter import *
class GUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.code_input = Entry(self)
self.code_input.pack()
self.barcode = Barcode(self, height=250, width=200)
self.barcode.pack()
Button(self, text="Update Barcode", command=self.barcode.draw).pack()

class Barcode(Canvas):
def __init__(self, master, height, width):
Canvas.__init__(self, master, height=height, width=width)
self.master = master
self.text = self.create_text((100,100))
def draw(self):
self.itemconfig(self.text, text=self.master.code_input.get())        
root = Tk()
gui = GUI(root)
gui.pack()
root.mainloop()

为了便于说明,我在画布上创建了一个文本对象,并在单击按钮时使用Entry的当前值进行更新。

最新更新