[python] Changing the text on a label

I am having trouble with using a key binding to change the value of a label or any parameter. This is my code:

from tkinter import*

class MyGUI:
  def __init__(self):
    self.__mainWindow = Tk()
    #self.fram1 = Frame(self.__mainWindow)
    self.labelText = 'Enter amount to deposit'
    self.depositLabel = Label(self.__mainWindow, text = self.labelText)
    self.depositEntry = Entry(self.__mainWindow, width = 10)
    self.depositEntry.bind('<Return>', self.depositCallBack)
    self.depositLabel.pack()
    self.depositEntry.pack()

    mainloop()

  def depositCallBack(self,event):
    self.labelText = 'change the value'
    print(self.labelText)

myGUI = MyGUI()

When I run this, I click the entrybox and hit enter, hoping that the label will change value to 'change the value'. However, while it does print that text, the label remains unchanged.

From looking at other questions on similar problems and issues, I have figured how to work with some of this outside a class, but I'm having some difficulties with doing it inside a class.

Also, on a side note, what role does "master" play in tkinter?

This question is related to python python-3.x tkinter

The answer is


Use the config method to change the value of the label:

top = Tk()

l = Label(top)
l.pack()

l.config(text = "Hello World", width = "50")

Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar

If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.

There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.

text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
                                                                    ^^^^^^^^^^^^^^^^^
  def depositCallBack(self,event):
      text.set('change the value')

There are many ways to tackle a problem like this. There are many ways to do this. I'm going to give you the most simple solution to this question I know. When changing the text of a label or any kind of wiget really. I would do it like this.

Name_Of_Label["text"] = "Your New Text"

So when I apply this knowledge to your code. It would look something like this.

from tkinter import*

class MyGUI:
   def __init__(self):
    self.__mainWindow = Tk()
    #self.fram1 = Frame(self.__mainWindow)
    self.labelText = 'Enter amount to deposit'
    self.depositLabel = Label(self.__mainWindow, text = self.labelText)
    self.depositEntry = Entry(self.__mainWindow, width = 10)
    self.depositEntry.bind('<Return>', self.depositCallBack)
    self.depositLabel.pack()
    self.depositEntry.pack()

    mainloop()

  def depositCallBack(self,event):
    self.labelText["text"] = 'change the value'
    print(self.labelText)

myGUI = MyGUI()

If this helps please let me know!


You can also define a textvariable when creating the Label, and change the textvariable to update the text in the label. Here's an example:

labelText = Stringvar()
depositLabel = Label(self, textvariable=labelText)
depositLabel.grid()

def updateDepositLabel(txt) # you may have to use *args in some cases
    labelText.set(txt)

There's no need to update the text in depositLabel manually. Tk does that for you.


I made a small tkinter application which is sets the label after button clicked

#!/usr/bin/env python
from Tkinter import *
from tkFileDialog import askopenfilename
from tkFileDialog import askdirectory


class Application:
    def __init__(self, master):
        frame = Frame(master,width=200,height=200)
        frame.pack()

        self.log_file_btn = Button(frame, text="Select Log File", command=self.selectLogFile,width=25).grid(row=0)
        self.image_folder_btn = Button(frame, text="Select Image Folder", command=self.selectImageFile,width=25).grid(row=1)
        self.quite_button = Button(frame, text="QUIT", fg="red", command=frame.quit,width=25).grid(row=5)

        self.logFilePath =StringVar()
        self.imageFilePath = StringVar()
        self.labelFolder = Label(frame,textvariable=self.logFilePath).grid(row=0,column=1)
        self.labelImageFile = Label(frame,textvariable = self.imageFilePath).grid(row = 1,column=1)

        def selectLogFile(self):
            filename = askopenfilename()
            self.logFilePath.set(filename)

        def selectImageFile(self):
            imageFolder = askdirectory()
            self.imageFilePath.set(imageFolder)

root = Tk()
root.title("Geo Tagging")
root.geometry("600x100")
app = Application(root)
root.mainloop()

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to tkinter

How can I create a dropdown menu from a List in Tkinter? Windows- Pyinstaller Error "failed to execute script " When App Clicked _tkinter.TclError: no display name and no $DISPLAY environment variable How to set a tkinter window to a constant size PermissionError: [Errno 13] Permission denied matplotlib error - no module named tkinter How do I change the text size in a label widget, python tkinter Tkinter understanding mainloop How to clear/delete the contents of a Tkinter Text widget? tkinter: Open a new window with a button prompt