【问题标题】:how to update label with a global variable如何使用全局变量更新标签
【发布时间】:2021-02-21 13:30:49
【问题描述】:

我正在尝试制作一个仅在更新标签上显示分数的分数系统 - 分数信息 (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()

edit: score1 =0 已添加但仍无法正常工作,标签显示但未更改

【问题讨论】:

  • label.config(text=score1)放在example函数的末尾
  • update 函数内调用root.after(100, update)。另外,def example 应该是 def example(): ,我相信 scoreIS = score1 应该是 scoreIS= example()。另外,请注意示例函数应返回 score1

标签: python tkinter label


【解决方案1】:

要更新标签的文本,您必须使用 .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,标签内的文本都会更新。

【讨论】:

  • 是的,现在好多了,谢谢。我只是复制了 OP 的代码,没有看到。
【解决方案2】:
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()

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

【讨论】:

  • 如果你有root.mainloop(),你就不需要root.update()。此外,变量 label 已经是全局变量,因此您甚至不需要 global label
【解决方案3】:

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

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()

【讨论】:

  • 这是非常低效的,因为方法update 将始终运行。将label["text"] = scrore1 放在所有更改score1 值的函数的末尾会更简单。此外,它每秒只会更新 10 次。 score 的值是多少需要更频繁地改变?
猜你喜欢
  • 2011-08-10
  • 2014-07-20
  • 2022-09-22
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多