【发布时间】:2021-10-01 21:01:19
【问题描述】:
我有一个带有两个输入框的 GUI:一个用于“最后换油英里数”,一个用于“当前英里数”。有一个按钮,单击该按钮会运行一个函数,该函数从输入框中读取输入并打印我到期或逾期的里程等。我想将输出显示到 GUI。我知道我必须创建一个标签小部件,但我该如何制作,以便当我按下按钮并调用函数时,标签文本会使用来自函数的信息进行更新?
from tkinter import *
from tkinter import ttk
#initializing root window
root = Tk()
root.title("Car Maintenance App")
#functions
miles = IntVar()
last_miles = IntVar()
def check_oil_change():
miles = miles_entry.get()
miles = int(miles)
last_miles = lastmiles_entry.get()
last_miles = int(last_miles)
miles_till_oilchange = 3000 - (miles - last_miles)
if miles_till_oilchange == 0:
print("You are due for an oil change")
if miles_till_oilchange > 0:
print("You have {} miles until next oil change.".format(miles_till_oilchange))
if miles_till_oilchange < 0:
print("You are over due {} miles for an oil change.".format(abs(miles_till_oilchange)))
#creating container for widgets
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
#widgets
milesLabel = ttk.Label(mainframe, text= "Enter your cars current mileage:")
lastmilesLabel = ttk.Label(mainframe, text= "How many miles was your last oil change at?")
miles_entry = ttk.Entry(mainframe, width=7)
lastmiles_entry = ttk.Entry(mainframe, width=7)
milesButton = ttk.Button(mainframe, text="Enter", command=check_oil_change)
#positioning
milesLabel.grid(row=1, column=0)
miles_entry.grid(row=1, column=1)
milesButton.grid(row=1, column=2)
lastmilesLabel.grid(row=0, column=0)
lastmiles_entry.grid(row=0, column=1)
root.mainloop()
【问题讨论】:
-
您好,欢迎来到 StackOverflow!在旁注中,我注意到您同时使用蛇肠衣和骆驼肠衣。我会选择一个(或者,比如说,使用驼峰式外壳来实现功能,而蛇形外壳来实现其他所有功能)。
-
@DanielWalker 谢谢!我可能会改用专门使用蛇壳。我不知道为什么我同时使用了这两个。