【发布时间】:2020-11-08 06:15:41
【问题描述】:
我是 Python 新手,并试图在 Python 3.8 中创建一个乘法表,使用标签数组来保存每个 Line 字符串。该代码有效,但在随后的 Button 单击时,它会将新的标签集附加到第一组标签的正下方,而不是首先清除它。
from tkinter import *
root = Tk()
sizex = 600; sizey = 400; posx = 0; posy = 0
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
labels = [] # creates an empty list for your labels
def showTable():
del labels[:] # delete any previous labels from window --> doesn't work?
nums = range(10)
tbl = entry.get()
for i in nums: # iterates over your nums
txt = tbl + ' x ' + str(i + 1) + ' = ' + str(int(tbl) * (i + 1))
label = Label(root, text = txt, bg = 'cyan') # set your text and random bgcolor --> how to randomize color?
# label.place(x = 10, y = 10 + (30 + i))
label.pack()
labels.append(label) # appends the label to the list for further use
entry = Entry(root)
entry.place(x = 50,y = 50) # doesn't place the textbox at given positions?
entry.pack()
btn = Button(root, text = 'Show Table', command = showTable)
btn.place(x = 100, y = 100) # doesn't place the button at given positions?
btn.pack()
root.mainloop()
我在我认为代码不起作用的地方添加了 cmets。在纠正和优化此代码时,任何帮助将不胜感激。另外,有没有办法随机化每行的背景颜色?
【问题讨论】:
-
您可以重复使用标签:预先创建标签,然后修改其内容,例如
label[i]['text] = "({} x {} = {}).format(arg1,arg2,arg3)"。如果您仍然想销毁一个小部件(可能是次优方法)迭代每个标签小部件并执行.destroy()。此外,您可以“隐藏”小部件(由pack几何经理制作)做label[i].pack_forget()。 -
@Space 你能把它作为答案发布吗?
-
anwser 已被接受,只是一个更正:要修改小部件的“属性”,请使用
label[i]["text"] = "({} x {} = {})".format(arg1,arg2,arg3)或label[i].configure(text="({} x {} = {})".format(arg1,arg2,arg3))。此外,我强烈建议您重复使用标签,而不是在每次迭代时销毁并重新创建它们。 -
@Space 重复使用是对的。我同意。我可以用重复使用标签的代码来补充我的答案吗?
-
@sifar 我补充了我的答案。
标签: python python-3.x for-loop tkinter