Python 3无法更新tkinter标签tex

2024-09-30 18:15:34 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我知道关于这个问题有很多线程,但我在这方面仍然没有取得任何进展,没有一个解决方案是有效的。我甚至创建了一个包含9行代码的最小示例,无论我做什么,标签文本都不会改变:

root = tkinter.Tk()

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

root.geometry("500x50" + "+" + str(screen_width - 520) + "+" + str(screen_height - 140))
root.title("POE Price Checker")
rootLabelHeader = tkinter.Label(root, text = "Currently searching:").pack()

labelText = tkinter.StringVar()
labelText.set("Nothing")
rootLabelInfo = tkinter.Label(root, text = labelText.get(), width=90).pack()

#rootLabelInfo.configure(text="New String") # Nope
#rootLabelInfo.config(text="New String") # Nope

labelText.set("Doesnt Work")
labelText.get()

#root.after(1000, ListenToInput)
root.mainloop()

首先,我尝试使用StringVar,但什么也没有发生,它从未将文本更改为“doesntwork”,也没有显示任何错误

然后我尝试使用:

rootLabelInfo.configure(text="New String")
rootLabelInfo.config(text="New String")

两者都给我NoneType object has no attribute config


Tags: text文本confignewstringtkinterrootwidth
1条回答
网友
1楼 · 发布于 2024-09-30 18:15:34

rootLabelInfo = tkinter.Label(root, text = labelText.get(), width=90).pack()将压缩对象函数(它将返回None)存储到rootLabelInfo

如果您计划以后使用小部件,请分两行操作:

rootLabelInfo = tkinter.Label(root, text = labelText.get(), width=90)
rootLabelInfo.pack()

另一种方法是使用StringVar并设置textvariable属性:

import tkinter

root = tkinter.Tk()

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

root.geometry("500x50" + "+" + str(screen_width - 520) + "+" + str(screen_height - 140))
root.title("POE Price Checker")
rootLabelHeader = tkinter.Label(root, text = "Currently searching:").pack()

labelText = tkinter.StringVar()
labelText.set("Nothing")
print(labelText.get())
rootLabelInfo = tkinter.Label(root, textvariable = labelText, width=90).pack()

labelText.set("New String")
print(labelText.get())

#root.after(1000, ListenToInput)
root.mainloop()

相关问题 更多 >