【问题标题】:Why can't I change my label text in tkinter (Python)?为什么我不能在 tkinter (Python) 中更改我的标签文本?
【发布时间】:2021-05-08 20:00:40
【问题描述】:

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

我收到此错误:

infoLabel.config(text = '这是介绍!') 文件 “C:\Python39\lib\tkinter_init_.py”,第 1646 行,在配置中 return self.configure('configure', cnf, kw) 文件“C:\Python39\lib\tkinter_init.py”,第 1636 行,在 _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()

【问题讨论】:

  • 你为什么在root.mainloop()之后打电话给myintro()root.mainloop() 在 tkinter 窗口被销毁时结束,因此标签不再存在
  • python def myintro(): my_variable = infoLabel.config(text = 'This is the intro!') my_variable_text = my_variable.get() 现在你可以在 mainloop 之后调用你的变量了。
  • @kirgizmustafa17 现在您正尝试致电<None>.get()。请注意,infoLabel.config(...) 不会返回任何有用的信息。

标签: python tkinter label


【解决方案1】:

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

myintro()
root.mainloop()

窗口标签将显示“This is the intro”。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多