Update Label Text in Python TkInter

前端 未结 3 1321
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 10:47

Is there any possible way to create a TkInter label that uses a string and a variable as the text?

For example:

name = \"bob\"
Label(root, text=\"hel         


        
3条回答
  •  臣服心动
    2021-01-07 11:17

    You must tell the label to change in some way.

    Here you have an example. The text of the label is a textvariable text defined as a StringVar which can be changed whenever you want with text.set().
    In the example, when you click the checkbox, a command change tells the label to change to a new value (here simplified to take two values, old and new)

    from Tkinter import Tk, Checkbutton, Label
    from Tkinter import StringVar, IntVar
    
    root = Tk()
    
    text = StringVar()
    text.set('old')
    status = IntVar()
    
    def change():
        if status.get() == 1:   # if clicked
            text.set('new')
        else:
            text.set('old')
    
    
    cb = Checkbutton(root, variable=status, command=change)
    lb = Label(root, textvariable=text)
    cb.pack()
    lb.pack()
    
    root.mainloop()
    

提交回复
热议问题