A First (Real) Example
https://tkdocs.com/tutorial/firstexample.html
Code
1 from tkinter import * 2 from tkinter import ttk 3 4 5 def calculate(*args): 6 try: 7 value = float(feet.get()) 8 meters.set((0.3048 * value * 10000.0 + 0.5) / 10000.0) 9 except ValueError: 10 pass 11 12 13 root = Tk() 14 root.title("Feet to Meters") 15 mainframe = ttk.Frame(root, padding="3 3 12 12") 16 # mainframe = ttk.Frame(root) 17 mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) 18 mainframe.columnconfigure(0, weight=1) 19 mainframe.rowconfigure(0, weight=1) 20 feet = StringVar() 21 meters = StringVar() 22 feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet) 23 feet_entry.grid(column=2, row=1, sticky=(W, E)) 24 ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E)) 25 ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, 26 sticky=W) 27 ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W) 28 ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E) 29 ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W) 30 for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) 31 32 for child in mainframe.winfo_children(): 33 print(child) 34 feet_entry.focus() 35 root.bind('<Return>', calculate) 36 root.mainloop()
FeetToMeters
1 from tkinter import * 2 from tkinter import ttk 3 4 5 class FeetToMeters: 6 7 def __init__(self, root): 8 root.title("Feet to Meters") 9 mainframe = ttk.Frame(root, padding="3 3 12 12",relief="groove",borderwidth=3) # padding=(左,上,右,下) 10 mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) 11 root.columnconfigure(0, weight=1) 12 root.rowconfigure(0, weight=1) 13 14 self.feet = StringVar(value=1) 15 feet_entry = ttk.Entry(mainframe, width=7, textvariable=self.feet) 16 feet_entry.grid(column=2, row=1, sticky=(W, E)) 17 self.meters = StringVar() 18 19 ttk.Label(mainframe, textvariable=self.meters).grid(column=2, row=2, sticky=(W, E)) 20 ttk.Button(mainframe, text="Calculate", command=self.calculate).grid(column=3, row=3, sticky=W) 21 22 ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W) 23 ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E) 24 ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W) 25 26 for child in mainframe.winfo_children(): 27 child.grid_configure(padx=5, pady=5) # 各组件之间上下左右的间距为5 ; 28 29 feet_entry.focus() # 窗口打开后光标自动移动到 输入框 ; 30 root.bind("<Return>", self.calculate) 31 32 def calculate(self, *args): 33 try: 34 value = float(self.feet.get()) 35 self.meters.set(int(0.3048 * value * 10000.0 + 0.5) / 10000.0) 36 except ValueError: 37 pass 38 39 40 if __name__ == '__main__': 41 root = Tk() 42 FeetToMeters(root) 43 root.mainloop()