如何从其他功能访问此文本小部件?

时间:2015-01-03 22:48:17

标签: python tkinter python-3.4

我正在尝试通过write_line函数将文本插入到我在 init 函数中创建的文本框中。我的目标是能够在文本框中动态添加文本,类似于命令控制台的工作方式(如果有更好的小部件或方法,请告诉我)。但是,我不确定如何从init函数外部访问文本小部件。我正在使用最新版本的python。

class Console(Text, Scrollbar):

    def __init__(self, parent):

        Text.__init__(self, parent)
        Scrollbar.__init__(self, parent)

        text = Text(parent)
        scroll = Scrollbar(parent)
        text.focus_set()

        scroll.pack(side=RIGHT, fill=Y)
        text.pack(side=LEFT, fill=Y)

        scroll.config(command=text.yview)
        text.config(yscrollcommand=scroll.set)

        # text.insert(END, 'this is a test') <-- need to move this statement to the write line function

    # write line to text box
    def write_line(self):

        pass

1 个答案:

答案 0 :(得分:1)

添加'自我'。在声明变量时,不要只是'text'而是变成'self.text'。

class Console(Text, Scrollbar):

    def __init__(self, parent):

        Text.__init__(self, parent)
        Scrollbar.__init__(self, parent)

        self.text = Text(parent)
        scroll = Scrollbar(parent)
        self.text.focus_set()

        scroll.pack(side=RIGHT, fill=Y)
        self.text.pack(side=LEFT, fill=Y)

        scroll.config(command=self.text.yview)
        self.text.config(yscrollcommand=scroll.set)

    # write line to text box
    def write_line(self):

        self.text.insert(END, 'this is a test') # there
相关问题