Python Tkinter 通过函数更新文本框内容

标签 python tkinter

这里是初学者程序员,正在制作一个基本的 GUI,作为我在网上关注的教程的一部分,但他们都没有说如何使用代码其他部分的输出来更新文本框。

我在网站上尝试了多个其他答案,包括一个使用 StringVar 的答案,这让我一无所获,另一个使用装饰器,其余的似乎超出了我的理解范围。

这是我的代码:

import tkinter as tk

import time
#Creating Root
root = tk.Tk()


#GUI TEMPLATE


frame =tk.Frame(root,
            height = 100,
            width = 400)
frame.pack()
v = StringVar()

colour = ["red","blue","green","white","yellow"]
labels = range(5) 
#change number to change how many labels
for i in range(5):
    l= tk.Label(root,
            text = colour[i],
            bg = colour[i])
    l.place(x = 10 +i*70, y = 10, width=60, height=25)




T1 = tk.Text(root, height=2, width=40)
words = "Don't name your files after module names!"
T1.insert(tk.END, textvariable=v)

T1.place(x = 10, y= 40)

S = tk.Scrollbar(root)
S.config(command=T1.yview)
S.place(x = 340, y=40)

T1.config(yscrollcommand=S.set)

root.mainloop()

v.set("Something Else!")

现在,它应该输出的是一行彩色标签(它可以正常工作)和一个带有滚动条的文本框(它应该立即更新为“Something Else!”),但它不能正常工作。

相反,我收到以下错误:

NameError:名称“StringVar”未定义

我知道这个错误意味着什么,只是我在寻找适合我的解决方案时遇到了困难,并且不需要博士学位才​​能理解。

我所要求的是是否有人能给我一个适用于此问题的解决方案,并希望能解释一下!

提前致谢。

编辑: 因此,在修复语法错误后,然后发现我想做的事情不起作用,我该如何解决这个问题?

我可以使用标签代替吗?或者还有其他更好的方法吗? 再次感谢!

最佳答案

StringVar 应通过 tk 访问:

v = tk.StringVar()

另一方面,tk.Text.insert 不采用 textvariable 参数,因此以下内容不起作用:

T1.insert(tk.END, textvariable=v)
#                 ^^^^^^^^^^^^??

来自docs :

Unlike for example the entry widget, text widgets don't support a "textvariable" configuration option

另请参阅How can I connect a StringVar to a Text widget in Python/Tkinter?至于为什么这行不通。

关于Python Tkinter 通过函数更新文本框内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40782228/

相关文章:

python - 投资组合优化的蒙特卡罗方法

python - 如何清除/删除 Tkinter Text 小部件的内容?

Python,在标签中的 Tkinter 中显示 openCv 图像

python - 带有 Tkinter 的 Python 中带有 CheckButtons 的列表框

python - 如何将 Tkinter Text 小部件中的图像绑定(bind)到事件?

python - 格式化 timedelta64 字符串输出

python - 为什么 PyCharm 看不到我的库?

python - float() 参数必须是字符串或数字,而不是 'zip'

python - 对seaborn histplot 中的重叠条有一些指示

python - 如何在滚动时保持小部件在 View 中?