如何使用全局变量更新标签

时间:2021-02-21 13:30:49

标签: python tkinter label

我正在尝试制作一个仅在更新标签上显示分数的分数系统 - 分数信息 (score1) 设置在另一个函数中,但我找不到解决方案。你可以忽略下面的代码,因为它只是我绝望的尝试和我缺乏理解


import tkinter
import random

score1 = 0
def example 
    global score1
    n = random.randint(1,3)
    if (n == 3)
        score1 = score1 + 1

label = tkinter.Label(root, text=score1, font = ('', 30))
label.pack()

def update():
    global score1
    scoreIS = score1
    label['text'] = scoreIS

root.after(100, update)
update()

root.mainloop()

编辑:添加了 score1 =0 但仍然不起作用,标签显示但没有改变

3 个答案:

答案 0 :(得分:0)

您必须在模块级别定义全局变量,然后才能在函数中覆盖它。将您的代码调整为以下内容:

import tkinter
import random

score1 = 0

def example 
    global score1
    n = random.randint(1,3)
    if (n == 3)
        score1 = score1 + 1

label = tkinter.Label(root, text=score1, font = ('', 30))
label.pack()

def update():
    global score1
    label['text'] = score1

root.after(100, update)
update()

root.mainloop()

答案 1 :(得分:0)

要更新标签的文本,您必须像这样使用 .config 方法:<tkinter.Label>.config(text=...)

带有标签的代码使用新文本进行配置:

import tkinter
import random

def example():
    global score1
    n = random.randint(1,3)
    if (n == 3):
        score1 += 1
    label.config(text=score1)

label = tkinter.Label(root, text=score1, font = ('', 30))
label.pack()

root.mainloop()

每次调用 example 时,标签内的文本都会更新。

答案 2 :(得分:0)

import tkinter as tk

# setup UI
root = tk.Tk()
label = tk.Label(root, text="0", font=('', 30))
label.pack()


def set_score(value):
    '''call this function only when the score is changed'''
    #global root # already global
    #global label #  already global
    label['text'] = str(value)
    #root.update() #don't need root.update() if you have root.mainloop()


set_score(100)  # any where you need to change score value
root.mainloop()

在我看来,创建一个纯函数来在需要时更新分数。