【发布时间】:2019-05-02 10:03:24
【问题描述】:
我正在制作条形码生成器。我需要类 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 以显示条形码
【问题讨论】:
-
更新:现在我正在尝试另一种结构,Barcode 类将消失,其功能移至 GUI 类。我对 OOP 标准的分数可能会降低,但没关系。我只需要让程序运行。但是我还是想知道在另一个类中使用一个类的变量的各种方法,比我想象的要难
-
.code是一个成员变量,如果不先创建一个GUI对象,您将无法访问它。 (旁注:我不使用 tkinter) -
看看我的回答here 用几个简单的例子来解释各种相关的概念。