使用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()中的,如果不设置它自动拉伸,设置输入框的拉伸不起作用。
网友评论