如何解决再次按下按钮后如何刷新窗口?
我是python的新手,我想用GUI制作更高级的程序。这是一个简单的计算器,可以按一定百分比计算股票利润。它询问价格和股票数量,然后以1-15%的增幅吐出利润。但是,再次按下Enter键后,标签只会打印在先前打印的标签上。我试图添加一个刷新按钮,但是那也不起作用。
from tkinter import *
root = Tk()
root.geometry("1280x720")
root.title("Profit Calculator")
share_label = Label(root,text="Shares: ")
share_label.grid(row=1,column=0)
price_label = Label(root,text="Price: ")
price_label.grid(row=0,column=0)
shares = Entry(root,)
shares.grid(row=1,column=1)
price = Entry(root,)
price.grid(row=0,column=1)
def profit_calculator():
cost = float(shares.get()) * float(price.get())
overall_cost = Label(root,text=("Overall Cost: $" + "{:.2f}".format(cost)))
overall_cost.grid(row=3,columnspan=2)
counter_of_percent = 1
for percent in range(1,16):
float(percent)
percentage = percent / 100
profit = cost * percentage
sell_price = float(price.get()) * (percentage + 1)
profit_at_percentage = Label(root,text="Sell Price at " + "{}".format(counter_of_percent) + "%: $" + "{:.2f}".format(sell_price) +
"\nProfit at " + "{}".format(counter_of_percent) + "%: $" + "{:.2f}".format(profit))
profit_at_percentage.grid(row=(4 + percent),columnspan=2)
counter_of_percent += 1
refresh = Button(root,text="Refresh",width=20,command=profit_at_percentage.destroy())
refresh.grid(row=20,columnspan=2)
enter = Button(root,text="Enter",command=profit_calculator)
enter.grid(row=2,columnspan=2)
root.mainloop()
解决方法
此处的关键是预先创建所有标签,然后使用该功能更新标签文本,而不是销毁先前的标签并重新创建它们。对于像标题这样的Label,将其移出函数很容易,但是对于在循环中创建的标签,我们需要将它们全部添加到列表中以进行跟踪。
from tkinter import *
root = Tk()
root.geometry("1280x720")
root.title("Profit Calculator")
share_label = Label(root,text="Shares: ")
share_label.grid(row=1,column=0)
price_label = Label(root,text="Price: ")
price_label.grid(row=0,column=0)
shares = Entry(root,)
shares.grid(row=1,column=1)
price = Entry(root,)
price.grid(row=0,column=1)
overall_cost = Label(root)
overall_cost.grid(row=3,columnspan=2)
profit_labels = []
for percent in range(1,16):
profit_at_percentage = Label(root)
profit_at_percentage.grid(row=(4 + percent),columnspan=2)
profit_labels.append(profit_at_percentage)
def profit_calculator():
cost = float(shares.get()) * float(price.get())
overall_cost.config(text=("Overall Cost: $" + "{:.2f}".format(cost)))
counter_of_percent = 1
for lbl in profit_labels:
float(percent)
percentage = percent / 100
profit = cost * percentage
sell_price = float(price.get()) * (percentage + 1)
lbl.config(text="Sell Price at " + "{}".format(counter_of_percent) + "%: $" + "{:.2f}".format(sell_price) +
"\nProfit at " + "{}".format(counter_of_percent) + "%: $" + "{:.2f}".format(profit))
counter_of_percent += 1
enter = Button(root,text="Enter",width=20,command=profit_calculator)
enter.grid(row=2,columnspan=2)
root.mainloop()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。