Python简易计算器(GPT-Cursor写的计算器)

闲来无事,利用Cursor写一个简易计算器

感觉写的还是非常好看的,这界面板板整整!

完整版代码:

import tkinter as tk

class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        # Create screen widget
        self.screen = tk.Entry(master, width=25, font=('Arial', 16))
        self.screen.grid(row=0, column=0, columnspan=4, padx=5, pady=5)

        # Create buttons
        self.create_button('7', 1, 0)
        self.create_button('8', 1, 1)
        self.create_button('9', 1, 2)
        self.create_button('/', 1, 3)

        self.create_button('4', 2, 0)
        self.create_button('5', 2, 1)
        self.create_button('6', 2, 2)
        self.create_button('*', 2, 3)

        self.create_button('1', 3, 0)
        self.create_button('2', 3, 1)
        self.create_button('3', 3, 2)
        self.create_button('-', 3, 3)

        self.create_button('0', 4, 0)
        self.create_button('.', 4, 1)
        self.create_button('C', 4, 2)
        self.create_button('+', 4, 3)

        self.create_button('=', 5, 0, columnspan=4)

    def create_button(self, text, row, column, columnspan=1, rowspan=1):
        button = tk.Button(self.master, text=text, width=5, height=2, font=('Arial', 16),
                           command=lambda: self.button_click(text))
        button.grid(row=row, column=column, columnspan=columnspan, rowspan=rowspan, padx=5, pady=5)

    def button_click(self, text):
        if text == '=':
            # Calculate the result
            try:
                result = eval(self.screen.get())
                self.screen.delete(0, tk.END)
                self.screen.insert(0, str(result))
            except:
                self.screen.delete(0, tk.END)
                self.screen.insert(0, "Error")
        elif text == 'C':
            # Clear the screen
            self.screen.delete(0, tk.END)
        else:
            # Add the button text to the end of the screen
            self.screen.insert(tk.END, text)

root = tk.Tk()
calculator = Calculator(root)
root.mainloop()

大家肯定会问,如何安装Cursor,在我的上一篇有写,点击:Cursor–gpt4国内可使用非常方便(保姆级教学)

希望得到大家的一个免费关注

你可能感兴趣的:(Python每日tips,python,gpt,开发语言,ui)