python-3.x - 如何在 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() 之后停止。
解决方案
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()
推荐阅读
- apache-spark - Spark 流式读取 azure 事件中心 - 错误编译
- vba - VBA url下载和重命名不成功
- c# - Azure Function 无法从设置中加载 CRON 计时器
- r - 我会根据前面(顶部)和结束(底部)聚合时间序列数据吗?
- ruby-on-rails - 调用中间属性
- python-3.x - 如何使用python将挪威日期格式转换为日期格式
- java - 如何访问 java 8 排序流中的前一项?
- sql - 如何在一个月内将日期拆分为 15 天间隔
- java - 如何在 Springfox Swagger 中将响应模型设置为一个类?
- c++ - OpenCL 内置函数选择