访问动态创建的 tkinter 小部件 [英] Accessing dynamically created tkinter widgets
本文介绍了访问动态创建的 tkinter 小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个 GUI,其中 tkinter 条目的数量由用户决定.
I am trying to make a GUI where the quantity of tkinter entries is decided by the user.
我的代码:
from tkinter import*
root = Tk()
def createEntries(quantity):
for num in range(quantity):
usrInput = Entry(root, text = num)
usrInput.pack()
createEntries(10)
root.mainloop()
此代码基于 本教程我发现:
for num in range(10):
btn = tkinter.button(window, text=num)
btn.pack(side=tkinter.LEFT)
问题是我只能访问最新创建的小部件中的输入,因为它们都具有相同的名称.有没有办法动态创建具有唯一名称的小部件?
The problem is that I can only access the input in the latest created widget, because they all have the same name. Is there a way of dynamically creating widgets with unique names?
任何建议将不胜感激
推荐答案
解决方案是将小部件存储在列表或字典等数据结构中.例如:
The solution is to store the widgets in a data structure such as a list or dictionary. For example:
entries = []
for num in range(quantity):
usrInput = Entry(root, text = num)
usrInput.pack()
entries.append(usrInput)
稍后,您可以遍历此列表以获取值:
Later, you can iterate over this list to get the values:
for entry in entries:
value = entry.get()
print("value: {}".format(value))
当然,您可以通过编号访问特定条目:
And, of course, you can access specific entries by number:
print("first item: {}".format(entries[0].get()))
这篇关于访问动态创建的 tkinter 小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文