python tkinter - 在按下按钮上写标签

时间:2018-05-16 09:55:55

标签: python tkinter label

 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个项目的购物清单。每个类别都有两个列表,item_name / item_price(它们已经从亚马逊中删除了。)

当我运行程序时,我可以按下按钮,列表将正确显示,但如果我再按一次,它会在之前制作的标签末尾添加新标签。我的问题是如何让程序覆盖以前的标签。按“购买电子产品”会根据需要创建我的标签,但在添加更多标签后按“购买书籍”。我想过来写“购买电子产品”标签。我认为它会是某种global lbl但不确定。

2 个答案:

答案 0 :(得分:1)

请参阅已创建函数的示例,为此需要覆盖,然后使用lbl["text"] = sv

将当前位置置于其中
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["text"] = sv
        sv.set(item_values)

然后在Labelroot

中创建mainloop
shop_window = Tk()

sv = StringVar()
lbl = Label(shop_window, height="2", textvariable=sv, anchor = NW)
lbl.grid(columnspan = 4)


shop_window = Tk()

答案 1 :(得分:1)

您可以为标签

创建一个框架
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()