How to change what is written on a Tkinter. Text in Python?

Asked

Viewed 20 times

0

In a tkinter.Entry, to change what is written I could put a StringVar in a textvariable and I could change this StringVar there is any moment that would be changed in the tkinter.Entry also

But in a widget tkinter.Text? I tried to use a StringVar and made a mistake.

My goal was to create an app where the user types anything and when the button is pressing all that text would be converted to uppercase, the code looked like this:

from tkinter import *


class Teste:
    def __init__( self ):
        self.app = Tk()
        self.app.title( 'Teste' )
        self.app.geometry( '700x700' )
        
        self.string = StringVar()
        
        self.txt = Text( self.app, textvariable=self.string )
        self.txt.pack()
        
        Button( self.app, text="Converter para Maiúsculo", command=self.converteMaiusculo ).pack()
        
        
        self.app.mainloop()
        
    def converteMaiusculo( self ):
        n = self.txt.get( "1.0", END )
        self.string.set( n.upper() )
        
        
myApp = Teste()

I didn’t know I couldn’t use a text or textvariable in a tkinter.Text, but then how could I do it?

1 answer

0

In this case it is not very necessary to use a Stringvar, you can take the contents, store in a string, delete everything inside Text and insert with upper

def converteMaiusculo( self ):
        n = self.txt.get( "1.0", END )
        self.txt.delete(1.0,END)
        self.txt.insert("insert",n.upper())

But if you want to use Stringvar with your Text you can use the Keyrelease bind for every time the user type anything, the bind perform a function to grab the text and set in Stringvar

Example:

def salvarStringVar(e): 
    self.string.set(self.txt.get("1.0",END))
    


self.txt.bind('<KeyRelease>',salvarStringVar)

Browser other questions tagged

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