如何为命名标签小部件创建循环。我不知道如何将小部件名称设置为变量。
from tkinter import *
def dofunc():
v1.set("one")
v2.set("two")
v3.set("three")
widget4.config(text="four")
v1=StringVar()
widget1=Label(root,width=10,textvariable=v1)
widget1.pack()
v2=StringVar()
widget2=Label(root,width=10,textvariable=v2)
widget2.pack()
v3=StringVar()
widget3=Label(root,width=10,textvariable=v3)
widget3.pack()
widget4=Label(root,width=10)
widget4.pack()
root.geometry("+50+50")
root.after(500, dofunc)
root.mainloop()
答案 0 :(得分:0)
我相信你要找的答案是容器吗?
bag_o_widgets = {} # A dict because you said "name", it could equally be an list with numbers for names.
def dofunc():
for i in range(1,4): # Generates 1,2 and 3 as inputs to the str() function for "naming".
v = StringVar()
bag_o_widgets[str(i)] = Label(root, width=10, textvariable=v)
bag_o_widgets[str(i)].pack()
bag_o_widgets["4"] = Label(root,width=10)
bag_o_widgets["4"].pack()
bag_o_widgets["4"].config(text="four")
return bag_o_widgets
这是在循环中命名变量的规范方法。
令人讨厌的文字黑客将改为使用多态代码。
答案 1 :(得分:0)
我用这种方式......
from tkinter import *
def dofunc():
bag_o_widgets[str(2)].config(text='two')
bag_o_widgets[str(5)].config(text='five')
bag_o_widgets[str(10)].config(text='ten')
bag_o_widgets[str(17)].config(text='seventeen')
root=Tk()
bag_o_widgets = {}
for i in range(1,21):
bag_o_widgets[str(i)] = Label(root, width=15)
bag_o_widgets[str(i)].pack()
root.after(100,dofunc)
root.mainloop()