我正在尝试使用for循环创建一个带有不确定数量的标签的GUI。 标签的数量应该是由按钮触发的功能改变的。 这是我的代码:
from tkinter import *
def change1():
print(days)
in1 = input('how many days?')
for a in range(0, len(days)):
days.remove(days[0])
for a in range(0, int(in1)):
in2 = input('type in another day: ')
days.append(in2)
krofl = (days[0], '-', days[len(days)-1])
firstlast.set(krofl)
Fenster = Tk()
Fenster.title("some title")
Fenster.minsize(width=800, height=900)
Fenster.resizable(width=FALSE, height=FALSE)
presetdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
days = []
for a in range(0, len(presetdays)):
days.append(presetdays[a])
firstlast = StringVar()
firstlast.set(str("preset value"))
lab1_1 = Label(Fenster, text='Zeitspanne:')
lab1_1.grid(row=0, column=0)
lab1_2 = Label(Fenster, textvariable = firstlast)
lab1_2.grid(row=0, column=1)
but1 = Button(Fenster, text='Change', command=change1)
but1.grid(row=0, column=2)
for a in range(0, len(days)):
karamel = Label(Fenster, text = days[a])
karamel.grid(row=a, column=6)
Fenster.mainloop()
我的问题是,即使在按下按钮后,标签列表也会是mon,tue .....改变日期清单。 我尝试过以下方法:
number_days = IntVar()
number_days.set(7)
并在def change1中添加:
sth = int(len(days))
number_days.set(sth)
并将for循环更改为:
for a in range(0, number_days):
karamel = Label(Fenster, text = days[a])
karamel.grid(row=a, column=6)
但它返回此错误: TypeError:' IntVar' object不能解释为整数
有没有办法让这个工作,以便所有的标签在def change1()之后更新?
答案 0 :(得分:1)
number_days
不是正常的整数变量。它是对象IntVar
。您必须使用number_days.get()
要更改标签,您必须记住列表中所有标签的karamel
(例如all_labels
),然后使用all_labels[number].config(text='new text')
或all_labels [数字] ['text'] ='新文字'`
您还可以使用some_label.grid_forget()
从网格中删除标签。
from tkinter import *
def change_labels():
print(days)
in1 = int(input('how many days?'))
# remove all old days
days.clear()
for a in range(in1):
in2 = input('type in another day: ')
days.append(in2)
krofl = (days[0], '-', days[-1])
firstlast.set(krofl)
# it is simpler to remove all labels and create new labels
# remove all old labels
for l in labels:
l.grid_forget()
# create new labels
for number, name in enumerate(days):
karamel = Label(Fenster, text=name)
karamel.grid(row=number, column=6)
labels.append(karamel)
# ---
presetdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
# copy list
days = presetdays[:]
# ---
Fenster = Tk()
Fenster.title("some title")
Fenster.minsize(width=800, height=900)
Fenster.resizable(width=FALSE, height=FALSE)
firstlast = StringVar()
firstlast.set(str("preset value"))
lab1_1 = Label(Fenster, text='Zeitspanne:')
lab1_1.grid(row=0, column=0)
lab1_2 = Label(Fenster, textvariable = firstlast)
lab1_2.grid(row=0, column=1)
but1 = Button(Fenster, text='Change', command=change_labels)
but1.grid(row=0, column=2)
# --- create labels first time
labels = []
for number, name in enumerate(days):
karamel = Label(Fenster, text=name)
karamel.grid(row=number, column=6)
labels.append(karamel)
Fenster.mainloop()