def button_pressed(item_name, item_price):
global lbl
for v1, v2 in zip(item_name, item_price):
item_values = '{} {}'.format(v1, v2)
sv = StringVar()
lbl = Label(shop_window, height="2", textvariable=sv, anchor = NW).grid(columnspan = 4)
sv.set(item_values)
# Create initial shopping cart window
shop_window = Tk()
shop_window.title('Welcome to the Outlet')
shop_window.geometry("1200x900")
shop_window.resizable(0, 0)
introduction_text = Label(shop_window, text = 'Welcome to the Shopping Outlet', font = ('Arial', 30))
electronics_button = Button(shop_window, text = 'Buy Electronics', font = ('Arial', 18), command = lambda:button_pressed(electronics_name, electronics_price))
books_button = Button(shop_window, text = 'Buy Books', font = ('Arial', 18), command = lambda:button_pressed(books_name, books_price))
kitchen_button = Button(shop_window, text = 'Buy Kitchen', font = ('Arial', 18), command = lambda:button_pressed(kitchen_name, kitchen_price))
monitors_button = Button(shop_window, text = 'Buy Kitchen', font = ('Arial', 18), command = lambda:button_pressed(monitors_name, monitors_price))
introduction_text.grid(row = 0, column = 0, columnspan = 4, sticky = N )
electronics_button.grid(row = 2, column = 0)
books_button.grid(row = 2, column = 1)
kitchen_button.grid(row = 2, column =2)
monitors_button.grid(row = 2, column = 3)
我创建了这个 tk 窗口来显示每个类别 10 件商品的购物 list 。每个类别都有两个列表,item_name/item_price(它们已从亚马逊上刮掉。)
当我运行程序时,我可以按下按钮,列表将正确显示,但如果我再次按下它,它会在之前制作的标签的末尾添加新标签。例如,我的问题是如何使程序覆盖以前的标签。按“购买电子产品”根据需要创建我的标签,但在添加更多标签后按“购买书籍”。我想重写“购买电子产品”标签。我认为这将是某种全局 lbl
但不确定。
最佳答案
您可以为标签创建一个框架
f = Frame(shop_window)
f.grid(row=3, column=0, columnspan=4)
然后在回调函数中销毁框架的所有子级并创建新的
def button_pressed(item_name, item_price):
for widget in f.winfo_children():
widget.destroy()
for v1, v2 in zip(item_name, item_price):
item_values = '{} {}'.format(v1, v2)
Label(f, height="2", text=item_values).pack()
关于python tkinter - 在按下按钮时重写标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50367735/