【问题标题】:python issue adds a new labelpython问题添加了一个新标签
【发布时间】:2022-11-13 04:41:26
【问题描述】:

看看这段代码 好吧,它恰好无缘无故地添加了另一个标签

import tkinter
from tkinter import *
clicks = 1
def click_count():

    global clicks

    # making the label that shows how many idk you have

    label = Label(frame, text="you have " + str(clicks), font=(('Courrier'), 32))
    label.pack()
    clicks += 1
    label.pack()




#generating the window
root = tkinter.Tk()
root.geometry('500x500')


#making the expandable frame
frame = Frame(root)
frame.pack(expand=YES)

#making the button
button = Button(frame, text= "click", font=(('Courrier'), 32), command=click_count)
button.pack()



root.mainloop()

然后我尝试了这个 我还尝试在最后删除 label.pack 但它仍然做同样的事情,即添加另一个标签

import tkinter
from tkinter import *
clicks = 1
def click_count():

    global clicks

    # making the label that shows how many idk you have

    label = Label(frame, text="you have " + str(clicks), font=(('Courrier'), 32))
    label.pack()
    label.destroy()
    clicks += 1
    label.pack()




#generating the window
root = tkinter.Tk()
root.geometry('500x500')


#making the expandable frame
frame = Frame(root)
frame.pack(expand=YES)

#making the button
button = Button(frame, text= "click", font=(('Courrier'), 32), command=click_count)
button.pack()



root.mainloop()

我期待它在标签上添加一个数字,但它只是显示另一个标签

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    它不会无缘无故添加标签。它添加了标签,因为这是您的函数告诉它要做的事情。每次单击按钮时,都会执行创建和打包新标签的函数。

    您应该做的是在开始时创建标签并将其链接到变量。然后,您可以在函数中更改此变量的值。

    此外,您不必两次导入 tkinter 并且先更新点击器然后显示结果而不是显示它具有的最后一个值是明智的。您的方法在这样一个小程序中有效,但clicks 的值总是比显示的高一个。因此,您在使用该值时可能会遇到问题。

    from tkinter import *
    
    def click_count():
        global clicks
        clicks += 1
        click_counter.set("you have " + str(clicks))
    
    #Initiate root
    root = Tk()
    root.geometry('500x500')
    
    #Set initial values for click counter
    clicks = 0
    click_counter = StringVar()
    click_counter.set("you have 0")
    
    #making the expandable frame
    frame = Frame(root)
    frame.pack(expand=YES)
    
    # making the label that shows how many idk you have
    label = Label(frame, textvariable=click_counter, font=(('Courrier'), 32)) ## The label gets updated, whenever the value of click_counter changes.
    label.pack()
    
    #making the button
    button = Button(frame, text= "click", font=(('Courrier'), 32), command=click_count)
    button.pack()
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多