tkinter界面设计 案例
时间: 2023-05-23 08:05:12 浏览: 317
A:以下是一个使用tkinter设计的简单计算器界面的案例:
```
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
self.create_display()
self.create_buttons()
def create_display(self):
self.display = tk.Entry(self.master, width=30, borderwidth=5, justify="right")
self.display.grid(column=0, row=0, columnspan=4, padx=10, pady=10)
def create_button(self, num):
button = tk.Button(self.master, text=num, padx=20, pady=10, command=lambda: self.button_click(num))
return button
def create_buttons(self):
self.button_1 = self.create_button("1")
self.button_2 = self.create_button("2")
self.button_3 = self.create_button("3")
self.button_4 = self.create_button("4")
self.button_5 = self.create_button("5")
self.button_6 = self.create_button("6")
self.button_7 = self.create_button("7")
self.button_8 = self.create_button("8")
self.button_9 = self.create_button("9")
self.button_0 = self.create_button("0")
self.button_dot = self.create_button(".")
self.button_add = self.create_button("+")
self.button_subtract = self.create_button("-")
self.button_multiply = self.create_button("x")
self.button_divide = self.create_button("/")
self.button_equal = self.create_button("=")
self.button_clear = self.create_button("C")
self.button_1.grid(row=1, column=0)
self.button_2.grid(row=1, column=1)
self.button_3.grid(row=1, column=2)
self.button_4.grid(row=2, column=0)
self.button_5.grid(row=2, column=1)
self.button_6.grid(row=2, column=2)
self.button_7.grid(row=3, column=0)
self.button_8.grid(row=3, column=1)
self.button_9.grid(row=3, column=2)
self.button_0.grid(row=4, column=1)
self.button_dot.grid(row=4, column=0)
self.button_add.grid(row=1, column=3)
self.button_subtract.grid(row=2, column=3)
self.button_multiply.grid(row=3, column=3)
self.button_divide.grid(row=4, column=3)
self.button_equal.grid(row=4, column=2)
self.button_clear.grid(row=5, column=1)
def button_click(self, num):
current = self.display.get()
self.display.delete(0, tk.END)
if num == ".":
if "." in current:
return
else:
self.display.insert(0, current + num)
elif num == "C":
self.display.delete(0, tk.END)
elif num == "=":
try:
result = eval(current)
self.display.insert(0, result)
except ZeroDivisionError:
self.display.insert(0, "Error")
except:
self.display.insert(0, "Invalid Input")
else:
self.display.insert(0, current + num)
root = tk.Tk()
my_calculator = Calculator(root)
root.mainloop()
```
该计算器界面包含数字、小数点、加号、减号、乘号、除号、等号、清除键,可以进行四则运算并显示结果。使用grid布局管理界面元素。界面响应使用lambda表达式绑定到相应的方法上。
阅读全文