简体   繁体   中英

How can I insert text in a text widget from another class in tkinter?

I'm trying to access a tkinter text widget from another class through instancing, but it's not being modified when called from outside class but works fine when the method is called inside the class.

I've also tried @staticmethod, though that doesn't seem to work either. I'd much prefer using an instanced object of the class though.

So here's the main:

if __name__ == "__main__":
    mainapp = tk.Tk()
    mainapp.title("Automatic Proofreader")
    mainapp.configure(background = "gray")
    mainapp.resizable(width = False, height = False)
    Core(mainapp).grid(column = 0, row = 0, sticky = 'news')
    TextDisplay(mainapp).grid(column = 5, row = 0, sticky = 'news')
    mainapp.mainloop()

Here's the class and the method I need to access:

class TextDisplay(tk.Frame):

    def setText(self, text):
        self.displayout.config(state = "normal")
        self.displayout.delete(1.0, tk.END)
        #This inserts nothing when called from outside class
        self.displayout.insert(tk.INSERT, text)
        #But it inserts the correct text when called from this same class
        self.displayout.config(state = "disabled")

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        verticalscroll = tk.Scrollbar(self)

        self.displayout = tk.Text(self, font = ('comic sans', 20, 'bold'), height = 20, width = 40, bg = "gray", wrap = tk.WORD, yscrollcommand = verticalscroll.set, state= "disabled")
        self.displayout.grid(columnspan = 4)

        verticalscroll.grid(column = 5, sticky = 'ns')
        verticalscroll.config(command = self.displayout.yview)

I'm first instancing this in another class like so self.displayclass = TextDisplay(mainapp)

and calling the method like so self.displayclass.setText(self.text)

I noticed in debugging, that the value of text variable inside the method is passed perfectly when called from outside the class (eg self.text gets passed correctly as text ). But the insertion does not work.

EDIT : By "not working" I meant that, it does not insert anything at all. Sorry for not being clear.

In short, to call a function on an object you must have a reference to an instance of the object. That's a fundamental aspect of object-oriented programming.

You don't necessarily have to use a global variable. You can, or you can store it as an attribute on some other object.

Here is a minimal example that works:

if __name__ == "__main__":
    mainapp = tk.Tk()
    displayclass = TextDisplay(mainapp)
    displayclass.grid(column = 5, row = 0, sticky = 'news')

    displayclass.setText("hello, world")
    mainapp.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM