简体   繁体   English

Tkinter 显示 Label 不更新

[英]Tkinter Display Label does not udpate

The displayed score on the Tkinter window does not update on each loop. Tkinter window 上显示的分数不会在每个循环上更新。 But if you check in the terminal score is been updated但是,如果您签入终端分数已更新

Tk Window does not update tk Window不更新在此处输入图像描述

The terminal score has been updated终端分数已更新在此处输入图像描述

score = 0

def check():
    global score
    if answered_question[1]['correct_answer'] == 'True':
        score += 1

root = tk.Tk()
root.config(padx=20, pady=20, bg=BLUE_GRAY)

score_board = tk.Label(
    text=f"Score: {score}",
    bg=BLUE_GRAY, fg="white",
    font=('Arial', 10, "normal")
)

check_btn = tk.Button(image=check_img, command=check, highlightthickness=0)

root.mainloop()

You have to update the label explicitly by using either config / configure (same thing), or by binding a tk.StringVar() to your Label 's textvariable parameter您必须通过使用config / configure (相同的东西)或通过将tk.StringVar()绑定到Labeltextvariable参数来显式更新 label

# Option One
def check():
    global score
    if answered_question[1]['correct_answer'] == 'True':
        score += 1
        # update the label
        score_board.configure(text=f'Score: {score}')

or...或者...

# Option Two
def check():
    global score
    if answered_question[1]['correct_answer'] == 'True':
        score += 1
        # update the label
        label_var.set(f'Score: {score}')

...  # code omitted for brevity

label_var = tk.StringVar()  # declare a tk.StringVar to bind to your label

score_board = tk.Label(
    text=f"Score: {score}",
    bg=BLUE_GRAY, fg="white",
    font=('Arial', 10, "normal"),
    textvariable=label_var,  # the label will update whenever this var is 'set'
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM