使用tkinter产生n个变量的n个标签 [英] Using tkinter to produce n labels where n is variable

查看:193
本文介绍了使用tkinter产生n个变量的n个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望实现一个顶层窗口,上面有可控制数量的标签小部件.在我的第一个窗口中,有一个比例小部件,可用于选择顶层的标签数量.这些标签然后需要实时更新.我有用于生成顶层窗口以及使用 After 实用工具动态更新其上一个标签的代码.

I'm looking to implement a top level window which has a controllable number of label widgets on it. In my first window, there is a scale widget which you can use to select the number of labels on the top level. These labels then need to be updated in real time. I have code for generating the top level window, as well as for dynamically updating one label on it using the After utility.

我不知道如何产生一组可变的标签,然后可以在代码中稍后对其进行更新.我的第一个想法是做这样的事情:

I can't figure out how to produce a variable set of labels which I can then update later in the code. My first thought is to do something like so:

for i in range(n):
  label = Label(top_level, text = "Text")
  label.pack()

问题在于它如何生成相同的标签n次,这意味着您不能独立(或根本)不更新它们.这意味着我无法实现我的 after 参数来用实时数据更新它们.解决此问题的正确方法是什么?

The issue with this is how it generates the same label n times and that means you can't update them independently (or at all). This means I can't implement my after argument to update them with real-time data. What is the correct way to approach this problem?

推荐答案

问题在于它如何生成n次相同的标签

The issue with this is how it generates the same label n times

这是不正确的.您要做创建了n个不同的标签,但是在循环的每次迭代中,您都覆盖了对前一个标签的引用.因此,当循环结束时,您只能引用最后一个标签.

This is incorrect. You do create n different labels, but in every iteration of the loop you overwrite the reference to the previous label. Therefore, when the loop ends, you have a reference to only the last label.

您可以做的是将不同的标签保存在列表中.这样,您可以使用它们的索引分别访问它们:

What you can do is save the different labels in a list. That way, you can access them individually using their index:

from tkinter import *

top_level = Tk()

n = 5
label_list = []

for i in range(n):
    label_list.append(Label(top_level, text = "Text"))
    label_list[i].pack()

for i in range(n):
    label_list[i].config(text="Text {}".format(i))

top_level.mainloop()

这篇关于使用tkinter产生n个变量的n个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆