首页 > 解决方案 > 如何在 Python 中使用 Tkinter 制作交互式标签

问题描述

我正在尝试使用 Tkinter 制作一个空闲游戏,但我不知道如何保留显示更新金额的标签。

我尝试使用 while 循环进行标签更新,但程序没有正确加载没有 mainloop() 的窗口。我已将 w.mainloop() 放入循环中,但现在它不再重复了。(w=Tk())

def money():
    File=open('./assets/save/money.txt','r')
    moneynow=File.read()
    File.close()
    try:
        if int(moneynow) >> 0 or int(moneynow) == 0:
            do='nothing'
    except:
        File=open('./assets/save/money.txt','w')
        File.write('0')
        File.close()
        w.destroy()

text1=Label(w,text='You currently have',bg='#CEE3F6',font=('arial black',10),fg='#820038')
text1.place(x=250,y=5)
text2=Label(w,text='$',bg='#CEE3F6',font=('arial black',10),fg='#820038')
text2.place(x=298,y=70)


#Interactive GUI
while True:
    money()
    File=open('./assets/save/money.txt','r')
    moneyamount=File.read()
    File.close()
    moneydisplay=Label(w,text=moneyamount,bg='#CEE3F6',font=('impact',40),fg='#FFCA4F',pady=-3)
    moneydisplay.place(x=289,y=25,height=45)
    w.mainloop()

预期结果:循环继续。

实际结果:循环不会重复,因为编译器在 w.mainloop() 之后停止。

标签: python-3.xtkinter

解决方案


mainloop是一直运行直到关闭窗口的循环。你必须使用after(time, function_name)它来发送它mainloop,它会在选择时间后运行它——这样它就会像在自己的循环中一样重复功能。

from tkinter import *

def update_money():
    with open('./assets/save/money.txt') as f:
        moneynow = f.read()

    try:
        if int(moneynow) < 0:
            with open('./assets/save/money.txt', 'w') as f:
                f.write('0')
        w.destroy()
    except:
        print('Cant convert')
        w.destroy()


    moneydisplay['text'] = moneynowe    
    w.after(1000, update_money) # run again after 1000ms (1s)

# --- main --  

w = Tk()

text1 = Label(w, text='You currently have')
text1.pack()

text2 = Label(w, text='$')
text2.pack()

moneydisplay = Label(w, text="") # empty label, I will put text later
moneydisplay.pack()

update_money() # put text first time

w.mainloop()

推荐阅读