我想在单击按钮(创建)时在另一个下面创建多个标签,然后在另一个按钮单击(删除)时删除一个实例中的所有标签
现在,我正在考虑为标签创建多个名称——每个名称只需单击一次即可创建。所以如果我点击按钮n次,我会得到n个名字:myLabel1,myLabel2,…,myLabeln
然后,当我点击删除按钮时,我会看到如下内容- myLabel1.destroy(), myLabel2.destroy(), . . . myLabeln.destroy()
我正在努力以-myLabel1=tk.Label等形式将这些名称分配给标签。 我用MATLAB中的求值函数来思考。Python有类似的功能吗
还有更好的方法来做我想做的事吗
如果我使用.pack()方法,我的标签会一个接一个。但它们都只分配给myLabel(因为我使用myLabel=tk.Label)。当我使用myLabel.destroy()时,只删除label的最后一个实例
使用.pack()和myLabel的单一用法编写代码,其中标签根据需要形成,但只删除最后一个标签:
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
root = tk.Tk()
def click():
global myLabel
myLabel = tk.Label(root, text = e.get())
myLabel.pack(pady=10)
e.delete(0,'end')
def delete():
myLabel.destroy()
e = tk.Entry(root, width = 50)
e.pack(padx = 10, pady = 10)
CreateButton = tk.Button(root, text = 'Enter name', command = click)
CreateButton.pack(pady=10)
DeleteButton = tk.Button(root, text = 'Delete', command = delete)
DeleteButton.pack(pady=40)
root.mainloop()
但由于这只会删除创建的最后一个标签,我尝试了我在开始时提到的方法-
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
ii = 0
root = tk.Tk()
def click():
global labelname, ii
ii += 1
labelname = 'myLabel' + str(ii)
print(labelname)
labelname = tk.Label(root, text = e.get()) # I wanted 'labelname' here to be 'myLabel1'
e.delete(0,'end')
def delete():
# for ii in range(1,max(ii)):
labelname.config(text = '') # I wanted 'labelname' here to be 'myLabeln' in a for loop going from 1 to n
e = tk.Entry(root, width = 50)
e.pack(padx = 10, pady = 10)
CreateButton = tk.Button(root, text = 'Enter name', command = click)
CreateButton.pack(pady=10)
DeleteButton = tk.Button(root, text = 'Delete', command = delete)
DeleteButton.pack(pady=40)
root.mainloop()
也许我会用一种非常复杂的方式来处理它,有一种更简单的方法不用For循环,等等
请给我一些建议
多谢各位
R
您可以使用这个脚本:每个标签的文本都存储在var标签中
您可以在新行中重新创建一个标签,而不是为每个标签指定一个变量,但可以将其添加到数组或类似于可以包含所有标签的数组中,这样您就可以随时删除每个标签
填写条目并单击按钮
可以使用网格来组织窗口。在这种情况下,请使用grid_forget和not pack_forget删除标签
相关问题 更多 >
编程相关推荐