[英]Label not updating in python tkinter
I'm writing a tkinter program, and I'm trying to update my label on the ui. 我正在编写一个tkinter程序,并且试图在ui上更新标签。 However I can't get it to work.
但是我无法正常工作。 Here's the code:
这是代码:
from tkinter import *
import random, functools, string
root = Tk()
word_list = ["APPLE", "PEAR", "BANNANA"]
word = word_list [random.randint(0,2)]
hidden_word = ["_ "] * len(word)
print (word)
abc = ['_ '] * len(word)
guessed_letters = []
#Functions
def click_1 (key):
if key in word:
guessed_letters = ''.join([key])
global abc
abc = ''.join([key if key in guessed_letters else "_" for key in word])
else:
print ("Nope") ####TESTING#####
#Frames
hangman_frame = Frame(root)
hangman_frame.grid(row=0, column=0, sticky=N)
letter_frame = Frame(root)
letter_frame.grid(row=1, column=0, sticky=S)
#Label
letters_label = Label(hangman_frame, textvariable=abc)
letters_label.grid(row=0, column=0, sticky=W)
(Just an excerpt, not all) (仅摘录,并非全部)
My question is that when ran, this section appears not to work: 我的问题是,当运行时,此部分似乎不起作用:
letters_label = Label(hangman_frame, textvariable=abc)
where: 哪里:
abc = ['_ '] * len(word)
guessed_letters = []
#Functions
def click_1 (key):
if key in word:
guessed_letters = ''.join([key])
global abc
abc = ''.join([key if key in guessed_letters else "_" for key in word])
And nothing shows up, whereas when this is put: 什么也没有出现,而当放置时:
letters_label = Label(hangman_frame, text=abc)
The label shows up, but does not update when the function click_1 is called. 标签会显示,但在调用click_1函数时不会更新。
Any reason to this? 有什么理由吗? Thanks in advance.
提前致谢。
The reason is that the textvariable
option requires an instance of StringVar
or IntVar
. 原因是
textvariable
选项需要StringVar
或IntVar
的实例。 You can't just pass it the name of a normal variable. 您不能只是将其传递给普通变量的名称。
Generally speaking, you never need to use the textvariable
option unless you specifically need the features of a StringVar
or IntVar
(such as having two widgets share the same data, or doing traces on the variable). 一般来说,除非特别需要
StringVar
或IntVar
(例如,让两个小部件共享同一数据,或者对变量进行跟踪),否则永远不需要使用textvariable
选项。 I know lots of examples use it, but it just adds another object that you don't really need. 我知道很多示例都使用它,但是它只是添加了您实际上不需要的另一个对象。
In order to update the text on a label, you would do this: 为了更新标签上的文本,您可以这样做:
letters_label = Label(..., text="initial value")
...
def click_1(...):
...
abc = ...
letters_label.configure(text=abc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.