学习tkinter之余,实现了一个简单的计算器操作,能够满足页面输入参数和计算得到结果 下面是结果展示和源码记录: 源码如下:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class Windows(tk.Frame):
def __init__(self, root):
self.root = root
self.root.geometry("300x200")
self.root.title("WIN")
self.frame1 = tk.Frame()
self.frame2 = tk.Frame()
self.operate = tk.Frame()
self.lable_str = tk.StringVar(None, "6666")
self.num1 = tk.StringVar(None, "")
self.num2 = tk.StringVar(None, "")
self.operate_str = tk.StringVar(None, "+")
self.lable_num1()
self.lable_num2()
self.lable_operate()
self.button_()
def lable_num1(self):
tk.Label(self.frame1, text="输入第1个数字").grid(row=0, column=0)
tk.Entry(self.frame1, textvariable=self.num1).grid(row=0, column=1)
self.frame1.grid()
def lable_num2(self):
tk.Label(self.frame2, text="输入第2个数字").grid(row=1, column=0)
tk.Entry(self.frame2, textvariable=self.num2).grid(row=1, column=1)
self.frame2.grid()
def button_(self):
tk.Button(self.root, text="输出结果", command=self.button_operate, width=6,
heigh=2).grid()
def lable_operate(self):
tk.Label(self.operate, text="运算符").grid(row=3, column=0)
self.selector = ttk.Combobox(self.operate, values=["+", "-", "*", "/", "//"])
self.selector.grid(row=3, column=1)
self.selector.current(0)
self.selector.bind("<<ComboboxSelected>>", self.selectlistenor)
self.operate.grid()
def selectlistenor(self, *args):
print("当前的运算符号为:%s" % self.selector.get())
self.operate_str.set(self.selector.get())
def button_operate(self):
num1 = int(self.num1.get())
num2 = int(self.num2.get())
operate = self.operate_str.get()
result = 0
print(num1)
print(num2)
if (0 == num1) and ("/" == operate or "//" == operate):
messagebox.showwarning("被除数不能为0")
return
if operate == "+":
result = num1 + num2
if operate == "-":
result = num1 - num2
if operate == "*":
result = num1 * num2
if operate == "/":
result = num1 / num2
if operate == "//":
result = num1 / num2
if num1 is None or num2 is None:
messagebox.showerror("\n提示:请输入要计算的数据")
return
messagebox.showinfo("%s" % (result))
if __name__ == '__main__':
root = tk.Tk()
Windows(root=root)
root.mainloop()
|