使用Python3自帶的GUI庫,定一個計算平方根的程序蝗肪。
from tkinter import *
import math
def root_value():
value = v.get()
try:
value = float(value)
out_entry.insert(0, math.sqrt(value))
except(ValueError):
out_entry.insert(0, f"{value} is not a number")
win = Frame()
win.pack(expand=YES, fill=BOTH)
# bind the text of entry
v = StringVar()
label = Label(win, text='Calculate square root!') # create a label
label.pack(side=TOP, expand=YES, fill=BOTH)
input_entry = Entry(win, textvariable=v)
input_entry.pack(side=TOP)
out_entry = Entry(win)
out_entry.pack(side=TOP, expand=YES, fill='x')
Button(win, text='Cal', command=root_value, bg='green').pack(side=LEFT)
button = Button(win, text="Exit", bg='red', command=sys.exit)
button.pack(side=RIGHT)
win.mainloop()
注意所有可見組件都是放在win這個Frame()中的袜爪,如果不設(shè)置它自動拉伸,設(shè)置輸入框的拉伸不起作用薛闪。