简体   繁体   中英

Python tkinter update visuals of label with text and variable

when i click the button in the tk window the label dosnt change. it is meant to change from money=0 to money=1. How can I update the visuals on the label?

Here is my code:

#imports
from tkinter import *
import random
import time

#varibles
money=0


#functions
def addmoney():
    global money
    money+=1
#window code
window=Tk()
#                              v-height in from top
window.geometry("450x600+735+240")
#                 w^  l^  ^width in from left

#widgtes
lm1=Label(window,height=2,width=20,text=("Money=",money))
btn1=Button(window,text=("Generate money!"),command=addmoney)

#positioning widgets
lm1.place(x=50,y=30,anchor=CENTER)
btn1.place(relx=0.5,y=200,anchor=CENTER)

#program code
window.mainloop()

If you want to use a Label with a variable you're going to have to use StringVar() in your program. This is an example program I made:

from tkinter import *
money=0
global money
root=Tk()
display=StringVar() #create variable to be displayed by label
def get_money():
    global money
    money += 1 
    display.set("Money: "+str(money)) #combines "Money: " with variable and displays on label
money_label=Label(root,textvariable=display) #text_variable is used for displaying a StringVar()
money_label.pack()
money_button=Button(root,text="Get money",command=get_money) #button for getting money
money_button.pack()
root.mainloop() #updates tkinter window

I hope I understood your question correctly!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM