【问题标题】:How do I differentiate labels when configuring them in tkinter?在 tkinter 中配置标签时如何区分标签?
【发布时间】:2018-09-11 02:39:21
【问题描述】:

基本上,我正在尝试制作一个每秒更新自身的变量列表,但我只能获取要更新的最后一个标签。我对 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.label。或者,更简洁:你可以使用一个像列表这样的容器来保存这些对象,而不是给它们一个名字。

标签: python tkinter label configure


【解决方案1】:

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

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),只要它们:

  • 不要以数字开头
  • 仅包含字母、数字和_'s
  • 不是保留的 Python 关键字/函数(虽然有可能,但不建议覆盖函数。)

【讨论】:

  • 感谢您的解释。
【解决方案2】:

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

这使我们可以使用更少的代码来轻松阅读我们正在做的事情。

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

【讨论】:

  • 非常感谢。
猜你喜欢
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多