当我点击tk窗口中的按钮时,标签dosnt会发生变化。它意味着从money = 0变为money = 1。如何更新标签上的视觉效果?
这是我的代码:
#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()
答案 0 :(得分:0)
如果您想将Label与变量一起使用,则必须在程序中使用StringVar()
。这是我制作的示例程序:
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
我希望我能正确理解你的问题!