How to print typed text in a Tkinter GUI on the console?

Asked

Viewed 84 times

0

I wanted to create a text in a window and, pressing a button, my text appear on the console. My code is this:

from tkinter import *
class janela:
    def __init__ (self, janela):
        self.frame=Frame()
        self.frame.config(height=300,width=300,bg='black')
        self.frame.pack()
        janela.config(bg='black')
        janela.title('TITULO')

        text1 = Text (self.frame, width=20, height=5)
        text1.pack()
        confirm = Button (self.frame, text='Confirmar texto', fg='red', command=
                            lambda: print(text1))
        confirm.pack()
            
            
jan1 = Tk()
janela(jan1)
jan1.mainloop()

1 answer

0


You did almost everything right, but missed noticing that the text is a attribute of your frame, not the frame itself. Note that, as it stands, your program is printing the object name (!frame.!text). To get the text, you need to add the method get. Below code with correction:

from tkinter import *
class janela:
    def __init__ (self, janela):
        self.frame=Frame()
        self.frame.config(height=300,width=300,bg='black')
        self.frame.pack()
        janela.config(bg='black')
        janela.title('TITULO')

        text1 = Text(self.frame, width=20, height=5)
        text1.pack()
        confirm = Button (self.frame, text='Confirmar texto', fg='red', command=
                            lambda: print(text1.get(1.0, "end-1c")))
        confirm.pack()
            
            
jan1 = Tk()
janela(jan1)
jan1.mainloop()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.