初学Python tkinter,利用目前所学编写一个简单的计算器练习一下。
预期效果:
1.能够实现加减乘除运算,
2.只能输入数字
3.通过按钮选择进行哪种运算。
4.结果框不能修改,智能复制
5.按清除按钮能够清除所有内容
from tkinter import * count = Tk() count.title("纯醪八盅@计算器") def clear(): v1.set("") v2.set("") v3.set("") def calc(): print(v1.get(),v2.get()) print(v4.get()) if v4.get()=="+": result = int(v1.get()) + int(v2.get()) elif v4.get()=="-": result = int(v1.get()) - int(v2.get()) elif v4.get()=="x": result = int(v1.get()) * int(v2.get()) else: result = int(v1.get()) / int(v2.get()) v3.set(result) def test(content): return content.isdigit() frame = Frame(count) frame.pack(padx=10,pady=10) v1=StringVar() v2=StringVar() v3=StringVar() testEnt = count.register(test) entry_1 = Entry(frame,width = 10,textvariable=v1,validate="key",validatecommand=(testEnt,"%P"))# entry_1.grid(row=0,column=0,padx=5,pady=5) v4=StringVar() v4.set("+") label = Label(frame,textvariable=v4).grid(row=0,column=1,padx=5,pady=5) entry_2 = Entry(frame,width = 10,textvariable=v2,validate="key",validatecommand=(testEnt,"%P")) entry_2.grid(row=0,column=2,padx=5,pady=5) label2 = Label(frame,text="=").grid(row=0,column=3,padx=5,pady=5) entry_3 = Entry(frame,width = 10,textvariable=v3,state ="readonly")#显示结果的区域只读,不可修改 entry_3.grid(row=0,column=4,padx=5,pady=5) def set1(): v4.set("+") def set2(): v4.set("-") def set3(): v4.set("x") def set4(): v4.set("/") button1 = Button(frame,text="+",command = set1).grid(row=1,column=1,padx=5,pady=5) button2 = Button(frame,text="-",command = set2).grid(row=1,column=2,padx=5,pady=5) button3 = Button(frame,text="x",command = set3).grid(row=1,column=3,padx=5,pady=5) button4 = Button(frame,text="/",command = set4).grid(row=1,column=4,padx=5,pady=5) button5 = Button(frame,text="清空",command = clear).grid(row=2,column=1,padx=5,pady=5) button6 = Button(frame,text="=",command=calc).grid(row=2,column=3,padx=5,pady=5) mainloop()
效果截图:
时间: 2024-10-12 09:09:26