简体   繁体   中英

Why can't I change my label text in tkinter (Python)?

I'm trying to set text for an existing label when myintro is initiated.

I'm getting this error:

infoLabel.config(text = 'This is the intro:') File "C:\Python39\lib\tkinter_ init _.py", line 1646, in configure return self. configure('configure', cnf, kw) File "C:\Python39\lib\tkinter_ init .py", line 1636, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) _tkinter.TclError: invalid command name ".!label"

from tkinter import *

#Window properties
root = Tk()
root.title('CIT 144 Final, XXXX XXXX')
root.geometry('400x275')



#===============Functions==================
 
def myintro():
    infoLabel.config(text = 'This is the intro!')
      
def main():
    return

def buttonOneClick():
    return

    

#==============Window widgets definitions=================
infoLabel = Label(root, text = 'x')
inputBox = Entry(root, width = 18)
buttonOne = Button(root, text = '>>', width=5, command=buttonOneClick)


infoLabel.grid(column=0,row=0)
inputBox.grid(column=0,row=2)
buttonOne.grid(column=0,row=3)


root.mainloop()
myintro()

The problem when using tkinter's mainloop is that it will act as a "while" loop until the GUI's closed. If you invert these two lines:

myintro()
root.mainloop()

the window label will display "This is the intro".

This is why I recommend using the "update" functions when using tkinter:

from tkinter import *

#Window properties
root = Tk()
root.title('CIT 144 Final, XXXX XXXX')
root.geometry('400x275')

running = True

#===============Functions==================
 
def myintro():
    infoLabel.config(text = 'This is the intro!')
    root.update()
    root.update_idletasks()
      
def main():
    return

def buttonOneClick():
    return

    

#==============Window widgets definitions=================
infoLabel = Label(root, text = 'x')
inputBox = Entry(root, width = 18)
buttonOne = Button(root, text = '>>', width=5, command=myintro)


infoLabel.grid(column=0,row=0)
inputBox.grid(column=0,row=2)
buttonOne.grid(column=0,row=3)

while running:
    try:
        root.update()
        root.update_idletasks()
    except:
        break

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