How do you put a Tkinter Text into a variable like str?

Asked

Viewed 46 times

2

I created this code and intended that when I click on print, automatically write in Terminal everything you wrote in Text:

from tkinter import *

janela=Tk()

#cores
branco="white"
preto="black"
cinza="gray"

#confg da janela
janela["bg"]=branco
janela.geometry("500x500+50+50")

#funções
def opa():
    print(texto.get())

#objetos da tela
framepri=LabelFrame(janela,bg=preto)
salvar=Button(janela,bg=preto,text="print",fg=branco,command=opa)
texto=Text(janela,bg=branco,fg=preto)

#posições dos objetos
framepri.pack(anchor=NW)
texto.pack(anchor=NW)
salvar.pack(anchor=NW)

#----------------------
janela.mainloop()`

but when compiling, executing, writing something on Text and tighten in print, that is the result:

    print(texto.get())
TypeError: get() missing 1 required positional argument: 'index1'

1 answer

0

It lacks parameters for the get who’s calling. If you look at the tutorials of the documentation itself notice the following:

Retrieving the Text After users have made any changes and submitted the form (for example), your program can Retrieve the Contents of the widget via the get method: thetext = text.get('1.0', 'end')

That is, the get that gets the text needs two parameters, one for the start position and the other for the end, also explained in the link I mentioned:

The two Parameters are the start and end position; end has the obvious meaning. You can provide Different start and end positions if you want to obtain only part of the text. You’ll see more on positions shortly.

The idea of these parameters is that we can only get part of the text if we want it.

To apply this in your code just change the function you have to:

def opa():
    texto_inserido = texto.get('1.0', 'end')

And now do what you have to do with that texto_inserido.

Browser other questions tagged

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