在 tkinter 中配置标签时如何区分它们?

How do I differentiate labels when configuring them in tkinter?

基本上,我试图制作一个每秒更新自己的变量列表,但我只能获取最后一个要更新的标签。我对 tkinter 不太熟悉,没有任何帮助。我认为主要问题是我已经在 def 中得到它,但我不知道任何其他方式,如果有人可以帮助我解决我的问题,甚至帮助彻底检查程序,那将不胜感激。

import time
import textwrap
from tkinter import Tk, Label, Button
from pathlib import Path

while True:
    print(textwrap.fill("Please enter the name that you entered for the main document. It must have the exact same characters and is case sensitive.", 70))
    Name = input()
    FileName = Name+".txt"
    P = Path(FileName)

    if P.exists():

        class MyFirstGUI:

            def __init__(self, master):

                with open(FileName, "r") as file:
                    global Points
                    global Item1
                    global Item2
                    global Item3
                    global PPC
                    global PPS
                    global Item1Cost
                    global Item2Cost
                    global Item3Cost
                    read = file.read().splitlines()
                    Points = read[0]
                    Item1 = read[1]
                    Item2 = read[2]
                    Item3 = read[3]
                    PPC = 1 + int(Item3)
                    PPS = int(Item1)*1 + int(Item2)*5
                    Item1Cost = read[6]
                    Item2Cost = read[7]
                    Item3Cost = read[8]
                    Points = int(Points) + int(PPS)

                VarList = [str(Points), str(Item1), str(Item2), str(Item3), str(PPC), str(PPS), str(Item1Cost), str(Item2Cost), str(Item3Cost)]

                with open(FileName, "w") as file:

                    for List in VarList:
                        file.write(List+'\n')

                root = Tk()
                self.master = master
                master.title("Menu")

                self.label = Label(master, text=Points, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=Item1, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=Item2, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=Item3, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=Item1Cost, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=Item2Cost, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=Item3Cost, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=PPC, anchor='w')
                self.label.pack(fill='both', padx=10)
                self.label = Label(master, text=PPS, anchor='w')
                self.label.pack(fill='both', padx=10)

                root.after(1000, self.task)

            def task(self):

                with open(FileName, "r") as file:
                    global Points
                    global Item1
                    global Item2
                    global Item3
                    global PPC
                    global PPS
                    global Item1Cost
                    global Item2Cost
                    global Item3Cost
                    read = file.read().splitlines()
                    Points = read[0]
                    Item1 = read[1]
                    Item2 = read[2]
                    Item3 = read[3]
                    PPC = 1 + int(Item3)
                    PPS = int(Item1)*1 + int(Item2)*5
                    Item1Cost = read[6]
                    Item2Cost = read[7]
                    Item3Cost = read[8]
                    Points = int(Points) + int(PPS)

                VarList = [str(Points), str(Item1), str(Item2), str(Item3), str(PPC), str(PPS), str(Item1Cost), str(Item2Cost), str(Item3Cost)]

                with open(FileName, "w") as file:

                    for List in VarList:
                        file.write(List+'\n')

                self.label.configure(text=Points)
                self.label.configure(text=Item1)
                self.label.configure(text=Item2)
                self.label.configure(text=Item3)
                root.after(1000, self.task)

        root = Tk()
        my_gui = MyFirstGUI(root)
        root.mainloop()

    else:
        print(textwrap.fill("You didn't enter a valid name, please try again.", 70))

您可以使用字典来存储所有标签,因为字典允许键和值之间的映射。这对您来说可能是什么样子的示例:

self.labels = {} #Creates an empty dictionary
self.labels["points"] = Label(master, text=Points, anchor='w')
self.labels["points"].pack.pack(fill='both', padx=10)
self.labels["Item1"] = Label(master, text=Item1, anchor='w')
self.labels["Item1"].pack(fill='both', padx=10)
#.... rest of labels here

或者,您可以使用列表来存储所有标签并使用索引访问每个标签。这样,您就不必在创建标签后手动打包每个标签:

self.labels = []
self.labels.append(Label(master, text=Points, anchor='w'))
self.labels.append(Label(master, text=Item1, anchor='w'))
self.labels.append(Label(master, text=Item2, anchor='w'))
#.... rest of labels here

for label in self.labels:
    label.pack(fill='both', padx=10)

最后,您可以为标签指定不同的名称。这可能是最明确最直接的选择:

self.points_label = Label(master, text=Points, anchor='w')
self.Item1_label = Label(master, text=Item1, anchor='w')
self.Item2_label = Label(master, text=Item2, anchor='w')
self.Item3_label = Label(master, text=Item3, anchor='w')
self.Item1Cost_label = Label(master, text=Item1Cost, anchor='w')
#.... rest of labels here. Don't forget to pack each one

记住:标识符名称可以是您想要的任何名称(它们 不必 必须只是 self.labeltkinter),只要它们:

  • 不要以数字开头
  • 仅包含字母、数字和_
  • 未保留 python keywords/functions(不建议覆盖函数,尽管这是可能的。)

这是一个使用几个列表来管理变量并更新它们的示例。

这使我们可以使用更少的代码,从而更容易阅读我们正在做的事情。

import textwrap
import tkinter as tk
from pathlib import Path

print(textwrap.fill("Please enter the name that you entered for the main document. It must have the exact same characters and is case sensitive.", 70))
Name = input()
file_name = "./{}.txt".format(Name)

if Path(file_name).exists() == True:

    class MyFirstGUI(tk.Tk):
        def __init__(self, fn):
            tk.Tk.__init__(self)
            self.title("Menu")
            self.file_name = fn
            self.var_list = []
            self.lbl_list = []

            with open(self.file_name, "r") as file:
                read = file.read().splitlines()
                self.var_list = [read[0], read[1], read[2], read[3], 1 + int(read[3]),
                                int(read[1])*1 + int(read[2])*5, read[6], read[7], read[8]]

            with open(self.file_name, "w") as file:
                for lst in self.var_list:
                    file.write("{}\n".format(lst))

            for i in range(9):
                self.lbl_list.append(tk.Label(self, text=self.var_list[i], anchor="w"))
                self.lbl_list[i].pack(fill='both', padx=10)

            self.task()

        def task(self):
            with open(self.file_name, "r") as file:
                read = file.read().splitlines()
                self.var_list = [read[0], read[1], read[2], read[3], 1 + int(read[3]),
                                int(read[1])*1 + int(read[2])*5, read[6], read[7], read[8]]

            self.var_list[0] = int(self.var_list[0]) + 1 # added this to visuallize some active change.

            with open(self.file_name, "w") as file:
                for lst in self.var_list:
                    file.write("{}\n".format(lst))

            for i in range(9):
                self.lbl_list[i].config(text=self.var_list[i])

            self.after(1000, self.task)


    app = MyFirstGUI(file_name)
    app.mainloop()

else:
    print(textwrap.fill("You didn't enter a valid name, please try again.", 70))