为什么我不能在 tkinter (Python) 中更改我的标签文本?

时间:2021-05-08 20:00:40

标签: python tkinter label

我正在尝试在启动 myintro 时为现有标签设置文本。

我收到此错误:

<块引用>

infoLabel.config(text = '这是介绍!') 文件 “C:\Python39\lib\tkinter_init_.py”,第 1646 行,在配置中 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:无效的命令名称“.!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()

1 个答案:

答案 0 :(得分:0)

使用 tkinter 的 mainloop 时的问题是它会充当“while”循环,直到 GUI 关闭。如果你反转这两行:

myintro()
root.mainloop()

窗口标签将显示“这是介绍”。

这就是我建议在使用 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