簡體   English   中英

Python Tkinter使用文本和變量更新標簽的視覺效果

[英]Python tkinter update visuals of label with text and variable

當我單擊tk窗口中的按鈕時,標簽劑量不會更改。 它的意思是從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()

如果要使用帶有變量的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

希望我能正確理解您的問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM