最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python的tkinter庫開發(fā)一個(gè)計(jì)算器的完整代碼

 更新時(shí)間:2025年07月07日 10:15:04   作者:搏博  
Python是一種非常適合快速開發(fā)的編程語言,它有著豐富的庫來支持圖形用戶界面(GUI)的開發(fā),在本教程中,我們將使用tkinter庫來創(chuàng)建一個(gè)簡單計(jì)算器,tkinter是Python的標(biāo)準(zhǔn)GUI庫,它是跨平臺的,并且內(nèi)置于大多數(shù)Python安裝中,需要的朋友可以參考下

一、功能需求        

我們希望實(shí)現(xiàn)的這個(gè)計(jì)算器應(yīng)用程序,具有以下特點(diǎn):

1.功能齊全:

  • 基本運(yùn)算:加、減、乘、除
  • 高級運(yùn)算:平方根、百分比、冪運(yùn)算
  • 三角函數(shù):sin、cos、tan
  • 對數(shù)運(yùn)算:自然對數(shù) (ln)、常用對數(shù) (log)
  • 常數(shù):π

2.用戶界面友好:

  • 清晰的顯示區(qū)域,分為歷史記錄和當(dāng)前表達(dá)式
  • 顏色區(qū)分不同類型的按鈕(數(shù)字、運(yùn)算符、功能鍵)
  • 響應(yīng)式字體大小,適應(yīng)長表達(dá)式
  • 支持鍵盤輸入,提高操作效率

3.使用說明:

  • 點(diǎn)擊按鈕或使用鍵盤輸入表達(dá)式
  • 按 "=" 或回車鍵計(jì)算結(jié)果
  • "C" 鍵清除所有內(nèi)容
  • "?" 鍵刪除最后一個(gè)字符
  • 三角函數(shù)接受角度值

二、完整代碼以及運(yùn)行效果

1.完整代碼

將以下代碼,復(fù)制到開發(fā)工具中,通過CMD,這個(gè)應(yīng)用程序可以直接運(yùn)行,無需額外安裝庫。如需擴(kuò)展功能,可以在代碼中添加更多的按鈕和對應(yīng)的計(jì)算方法。

import tkinter as tk
from tkinter import font
import math
import re

class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("高級計(jì)算器")
        self.root.geometry("400x600")
        self.root.resizable(False, False)
        self.root.configure(bg="#f0f0f0")
        
        # 設(shè)置字體
        self.display_font = font.Font(family="SimHei", size=24)
        self.button_font = font.Font(family="SimHei", size=14)
        
        # 計(jì)算變量
        self.current_expression = ""
        self.last_result = ""
        self.is_new_calculation = True
        
        # 創(chuàng)建界面
        self._create_display()
        self._create_buttons()
        
        # 綁定鍵盤事件
        self.root.bind("<Key>", self._handle_key_event)
    
    def _create_display(self):
        # 歷史記錄顯示
        self.history_frame = tk.Frame(self.root, bg="#f0f0f0", height=50)
        self.history_frame.pack(fill=tk.X, padx=10, pady=(10, 0))
        self.history_frame.pack_propagate(0)
        
        self.history_label = tk.Label(
            self.history_frame, 
            text="", 
            bg="#f0f0f0", 
            fg="#888", 
            font=self.display_font,
            anchor=tk.E
        )
        self.history_label.pack(fill=tk.BOTH, padx=5)
        
        # 當(dāng)前表達(dá)式顯示
        self.display_frame = tk.Frame(self.root, bg="#f0f0f0", height=80)
        self.display_frame.pack(fill=tk.X, padx=10, pady=5)
        self.display_frame.pack_propagate(0)
        
        self.display = tk.Entry(
            self.display_frame, 
            font=self.display_font, 
            bg="white", 
            fg="black", 
            justify=tk.RIGHT,
            bd=5,
            relief=tk.SUNKEN
        )
        self.display.pack(fill=tk.BOTH, padx=5, pady=5)
        self.display.insert(0, "0")
        self.display.configure(state="readonly")
    
    def _create_buttons(self):
        button_frame = tk.Frame(self.root, bg="#f0f0f0")
        button_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 定義按鈕布局
        buttons = [
            ("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3), ("C", 1, 4),
            ("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3), ("?", 2, 4),
            ("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3), ("(", 3, 4),
            ("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3), (")", 4, 4),
            ("%", 5, 0), ("√", 5, 1), ("^", 5, 2), ("π", 5, 3), ("sin", 5, 4),
            ("cos", 6, 0), ("tan", 6, 1), ("ln", 6, 2), ("log", 6, 3), ("1/x", 6, 4)
        ]
        
        # 創(chuàng)建按鈕
        for button_data in buttons:
            text, row, col = button_data
            
            # 設(shè)置按鈕樣式
            if text == "=":
                bg_color = "#4CAF50"
                fg_color = "white"
            elif text == "C" or text == "?":
                bg_color = "#f44336"
                fg_color = "white"
            elif col == 3 or col == 4:
                bg_color = "#2196F3"
                fg_color = "white"
            else:
                bg_color = "#e0e0e0"
                fg_color = "black"
            
            # 創(chuàng)建按鈕
            button = tk.Button(
                button_frame,
                text=text,
                font=self.button_font,
                bg=bg_color,
                fg=fg_color,
                relief=tk.RAISED,
                bd=3,
                padx=10,
                pady=10,
                command=lambda txt=text: self._button_click(txt)
            )
            
            # 設(shè)置按鈕網(wǎng)格
            button.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
        
        # 設(shè)置網(wǎng)格權(quán)重,使按鈕均勻分布
        for i in range(7):
            button_frame.grid_rowconfigure(i, weight=1)
        for i in range(5):
            button_frame.grid_columnconfigure(i, weight=1)
    
    def _button_click(self, text):
        # 處理按鈕點(diǎn)擊事件
        if text == "C":
            self._clear_all()
        elif text == "?":
            self._backspace()
        elif text == "=":
            self._calculate()
        elif text == "π":
            self._append_value(str(math.pi))
        elif text == "√":
            self._calculate_sqrt()
        elif text == "^":
            self._append_value("**")
        elif text == "sin":
            self._calculate_trig("sin")
        elif text == "cos":
            self._calculate_trig("cos")
        elif text == "tan":
            self._calculate_trig("tan")
        elif text == "ln":
            self._calculate_ln()
        elif text == "log":
            self._calculate_log()
        elif text == "1/x":
            self._calculate_reciprocal()
        elif text == "%":
            self._calculate_percentage()
        else:
            self._append_value(text)
    
    def _handle_key_event(self, event):
        # 處理鍵盤事件
        key = event.char
        
        if key.isdigit() or key in "+-*/().":
            self._append_value(key)
        elif key == "\r" or key == "=":
            self._calculate()
        elif key == "\x08":  # Backspace
            self._backspace()
        elif key.lower() == "c":
            self._clear_all()
    
    def _append_value(self, value):
        # 追加值到當(dāng)前表達(dá)式
        if self.is_new_calculation:
            self.current_expression = ""
            self.is_new_calculation = False
        
        if self.current_expression == "0" and value.isdigit():
            self.current_expression = value
        else:
            self.current_expression += value
        
        self._update_display()
    
    def _clear_all(self):
        # 清除所有內(nèi)容
        self.current_expression = ""
        self.history_label.config(text="")
        self.is_new_calculation = True
        self._update_display()
    
    def _backspace(self):
        # 刪除最后一個(gè)字符
        if not self.is_new_calculation and self.current_expression:
            self.current_expression = self.current_expression[:-1]
            self._update_display()
    
    def _update_display(self):
        # 更新顯示內(nèi)容
        self.display.configure(state="normal")
        self.display.delete(0, tk.END)
        
        # 格式化顯示內(nèi)容
        display_text = self.current_expression
        
        # 檢查表達(dá)式長度,如果太長則縮小字體
        if len(display_text) > 15:
            self.display_font.configure(size=18)
        else:
            self.display_font.configure(size=24)
        
        self.display.insert(0, display_text)
        self.display.configure(state="readonly")
    
    def _calculate(self):
        # 計(jì)算表達(dá)式結(jié)果
        if not self.current_expression or self.is_new_calculation:
            return
        
        try:
            # 替換π和e
            expression = self.current_expression
            expression = re.sub(r'π', str(math.pi), expression)
            expression = re.sub(r'e', str(math.e), expression)
            
            # 計(jì)算結(jié)果
            result = eval(expression)
            
            # 格式化結(jié)果
            if isinstance(result, float):
                # 處理浮點(diǎn)數(shù)精度
                if result.is_integer():
                    result = int(result)
                else:
                    result = round(result, 10)
            
            # 更新歷史記錄
            self.history_label.config(text=f"{self.current_expression} = {result}")
            
            # 更新當(dāng)前表達(dá)式
            self.current_expression = str(result)
            self.last_result = str(result)
            self.is_new_calculation = True
            
            self._update_display()
            
        except Exception as e:
            self.display.configure(state="normal")
            self.display.delete(0, tk.END)
            self.display.insert(0, "錯(cuò)誤")
            self.display.configure(state="readonly")
            self.current_expression = ""
            self.is_new_calculation = True
    
    def _calculate_sqrt(self):
        # 計(jì)算平方根
        if not self.current_expression or self.is_new_calculation:
            return
        
        try:
            value = float(self.current_expression)
            if value < 0:
                raise ValueError("平方根不能為負(fù)數(shù)")
            
            result = math.sqrt(value)
            
            # 更新歷史記錄
            self.history_label.config(text=f"√{self.current_expression} = {result}")
            
            # 更新當(dāng)前表達(dá)式
            self.current_expression = str(result)
            self.last_result = str(result)
            self.is_new_calculation = True
            
            self._update_display()
            
        except Exception as e:
            self.display.configure(state="normal")
            self.display.delete(0, tk.END)
            self.display.insert(0, "錯(cuò)誤")
            self.display.configure(state="readonly")
            self.current_expression = ""
            self.is_new_calculation = True
    
    def _calculate_trig(self, func):
        # 計(jì)算三角函數(shù)
        if not self.current_expression or self.is_new_calculation:
            return
        
        try:
            value = float(self.current_expression)
            # 假設(shè)輸入是角度,轉(zhuǎn)換為弧度
            radians = math.radians(value)
            
            if func == "sin":
                result = math.sin(radians)
            elif func == "cos":
                result = math.cos(radians)
            elif func == "tan":
                result = math.tan(radians)
            else:
                result = "錯(cuò)誤"
            
            # 更新歷史記錄
            self.history_label.config(text=f"{func}({self.current_expression}°) = {result}")
            
            # 更新當(dāng)前表達(dá)式
            self.current_expression = str(result)
            self.last_result = str(result)
            self.is_new_calculation = True
            
            self._update_display()
            
        except Exception as e:
            self.display.configure(state="normal")
            self.display.delete(0, tk.END)
            self.display.insert(0, "錯(cuò)誤")
            self.display.configure(state="readonly")
            self.current_expression = ""
            self.is_new_calculation = True
    
    def _calculate_ln(self):
        # 計(jì)算自然對數(shù)
        if not self.current_expression or self.is_new_calculation:
            return
        
        try:
            value = float(self.current_expression)
            if value <= 0:
                raise ValueError("對數(shù)的真數(shù)必須大于0")
            
            result = math.log(value)
            
            # 更新歷史記錄
            self.history_label.config(text=f"ln({self.current_expression}) = {result}")
            
            # 更新當(dāng)前表達(dá)式
            self.current_expression = str(result)
            self.last_result = str(result)
            self.is_new_calculation = True
            
            self._update_display()
            
        except Exception as e:
            self.display.configure(state="normal")
            self.display.delete(0, tk.END)
            self.display.insert(0, "錯(cuò)誤")
            self.display.configure(state="readonly")
            self.current_expression = ""
            self.is_new_calculation = True
    
    def _calculate_log(self):
        # 計(jì)算常用對數(shù)
        if not self.current_expression or self.is_new_calculation:
            return
        
        try:
            value = float(self.current_expression)
            if value <= 0:
                raise ValueError("對數(shù)的真數(shù)必須大于0")
            
            result = math.log10(value)
            
            # 更新歷史記錄
            self.history_label.config(text=f"log({self.current_expression}) = {result}")
            
            # 更新當(dāng)前表達(dá)式
            self.current_expression = str(result)
            self.last_result = str(result)
            self.is_new_calculation = True
            
            self._update_display()
            
        except Exception as e:
            self.display.configure(state="normal")
            self.display.delete(0, tk.END)
            self.display.insert(0, "錯(cuò)誤")
            self.display.configure(state="readonly")
            self.current_expression = ""
            self.is_new_calculation = True
    
    def _calculate_reciprocal(self):
        # 計(jì)算倒數(shù)
        if not self.current_expression or self.is_new_calculation:
            return
        
        try:
            value = float(self.current_expression)
            if value == 0:
                raise ZeroDivisionError("不能除以零")
            
            result = 1 / value
            
            # 更新歷史記錄
            self.history_label.config(text=f"1/{self.current_expression} = {result}")
            
            # 更新當(dāng)前表達(dá)式
            self.current_expression = str(result)
            self.last_result = str(result)
            self.is_new_calculation = True
            
            self._update_display()
            
        except Exception as e:
            self.display.configure(state="normal")
            self.display.delete(0, tk.END)
            self.display.insert(0, "錯(cuò)誤")
            self.display.configure(state="readonly")
            self.current_expression = ""
            self.is_new_calculation = True
    
    def _calculate_percentage(self):
        # 計(jì)算百分比
        if not self.current_expression or self.is_new_calculation:
            return
        
        try:
            value = float(self.current_expression)
            result = value / 100
            
            # 更新歷史記錄
            self.history_label.config(text=f"{self.current_expression}% = {result}")
            
            # 更新當(dāng)前表達(dá)式
            self.current_expression = str(result)
            self.last_result = str(result)
            self.is_new_calculation = True
            
            self._update_display()
            
        except Exception as e:
            self.display.configure(state="normal")
            self.display.delete(0, tk.END)
            self.display.insert(0, "錯(cuò)誤")
            self.display.configure(state="readonly")
            self.current_expression = ""
            self.is_new_calculation = True

if __name__ == "__main__":
    root = tk.Tk()
    app = Calculator(root)
    root.mainloop()    

2.運(yùn)行效果

打開CMD,寫上“py+空格”,將文件拖入,回車運(yùn)行即可。

三、代碼詳細(xì)解析

這個(gè)計(jì)算器應(yīng)用程序基于 Python 的 tkinter 庫開發(fā),具有友好的用戶界面和豐富的計(jì)算功能。下面我將從整體架構(gòu)到具體功能逐步解析代碼:

1.整體架構(gòu)

代碼采用面向?qū)ο蟮姆绞浇M織,核心是Calculator類,它負(fù)責(zé):

  • 創(chuàng)建和管理圖形界面
  • 處理用戶輸入(按鈕點(diǎn)擊和鍵盤事件)
  • 執(zhí)行計(jì)算邏輯
  • 更新顯示內(nèi)容

2.初始化與界面設(shè)置

Calculator類中有一個(gè)初始化方法__init__(),實(shí)例化了一個(gè)GUI對象,并設(shè)置標(biāo)題、窗體大小、是否可放大縮小,以及背景顏色配置。

class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("高級計(jì)算器")
        self.root.geometry("400x600")
        self.root.resizable(False, False)
        self.root.configure(bg="#f0f0f0")
        
        # 設(shè)置字體
        self.display_font = font.Font(family="SimHei", size=24)
        self.button_font = font.Font(family="SimHei", size=14)
        
        # 計(jì)算變量
        self.current_expression = ""
        self.last_result = ""
        self.is_new_calculation = True
        
        # 創(chuàng)建界面
        self._create_display()
        self._create_buttons()
        
        # 綁定鍵盤事件
        self.root.bind("<Key>", self._handle_key_event)

代碼說明:

  • 窗口大小固定為 400x600 像素,不可調(diào)整
  • 使用兩種字體分別顯示表達(dá)式和按鈕文本
  • 三個(gè)關(guān)鍵變量:
    • current_expression:當(dāng)前輸入的表達(dá)式
    • last_result:上一次計(jì)算的結(jié)果
    • is_new_calculation:標(biāo)記是否開始新的計(jì)算

3.顯示區(qū)域設(shè)計(jì)

包括當(dāng)前輸入的內(nèi)容和上一次的計(jì)算記錄,上一次的計(jì)算記錄放在輸入框上面。

def _create_display(self):
    # 歷史記錄顯示
    self.history_frame = tk.Frame(self.root, bg="#f0f0f0", height=50)
    self.history_frame.pack(fill=tk.X, padx=10, pady=(10, 0))
    self.history_frame.pack_propagate(0)
    
    self.history_label = tk.Label(
        self.history_frame, 
        text="", 
        bg="#f0f0f0", 
        fg="#888", 
        font=self.display_font,
        anchor=tk.E
    )
    self.history_label.pack(fill=tk.BOTH, padx=5)
    
    # 當(dāng)前表達(dá)式顯示
    self.display_frame = tk.Frame(self.root, bg="#f0f0f0", height=80)
    self.display_frame.pack(fill=tk.X, padx=10, pady=5)
    self.display_frame.pack_propagate(0)
    
    self.display = tk.Entry(
        self.display_frame, 
        font=self.display_font, 
        bg="white", 
        fg="black", 
        justify=tk.RIGHT,
        bd=5,
        relief=tk.SUNKEN
    )
    self.display.pack(fill=tk.BOTH, padx=5, pady=5)
    self.display.insert(0, "0")
    self.display.configure(state="readonly")

代碼說明:

  • 分為兩個(gè)顯示區(qū)域:
    • 歷史記錄:顯示上一次的計(jì)算表達(dá)式和結(jié)果
    • 當(dāng)前表達(dá)式:顯示正在輸入的內(nèi)容
  • 使用pack_propagate(0)固定框架大小
  • 顯示區(qū)域使用凹陷邊框 (relief=tk.SUNKEN) 增強(qiáng)視覺效果

4.按鈕布局與設(shè)計(jì)

所有的按鈕用列表保存。

def _create_buttons(self):
    button_frame = tk.Frame(self.root, bg="#f0f0f0")
    button_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    
    # 定義按鈕布局
    buttons = [
        ("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3), ("C", 1, 4),
        ("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3), ("?", 2, 4),
        ("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3), ("(", 3, 4),
        ("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3), (")", 4, 4),
        ("%", 5, 0), ("√", 5, 1), ("^", 5, 2), ("π", 5, 3), ("sin", 5, 4),
        ("cos", 6, 0), ("tan", 6, 1), ("ln", 6, 2), ("log", 6, 3), ("1/x", 6, 4)
    ]
    
    # 創(chuàng)建按鈕
    for button_data in buttons:
        text, row, col = button_data
        
        # 設(shè)置按鈕樣式
        if text == "=":
            bg_color = "#4CAF50"  # 綠色
            fg_color = "white"
        elif text == "C" or text == "?":
            bg_color = "#f44336"  # 紅色
            fg_color = "white"
        elif col == 3 or col == 4:
            bg_color = "#2196F3"  # 藍(lán)色
            fg_color = "white"
        else:
            bg_color = "#e0e0e0"  # 灰色
            fg_color = "black"
            
        # 創(chuàng)建按鈕并綁定事件
        ...

代碼說明:

  • 使用 6x5 網(wǎng)格布局所有按鈕
  • 不同功能的按鈕使用不同顏色區(qū)分:
    • 等號:綠色
    • 清除和退格:紅色
    • 運(yùn)算符和功能鍵:藍(lán)色
    • 數(shù)字鍵:灰色
  • 使用grid方法排列按鈕,并設(shè)置sticky="nsew"使其填充整個(gè)單元格

5.核心計(jì)算功能

def _calculate(self):
    # 計(jì)算表達(dá)式結(jié)果
    if not self.current_expression or self.is_new_calculation:
        return
    
    try:
        # 替換π和e
        expression = self.current_expression
        expression = re.sub(r'π', str(math.pi), expression)
        expression = re.sub(r'e', str(math.e), expression)
        
        # 計(jì)算結(jié)果
        result = eval(expression)
        
        # 格式化結(jié)果
        if isinstance(result, float):
            if result.is_integer():
                result = int(result)
            else:
                result = round(result, 10)
        
        # 更新歷史記錄和顯示
        ...
        
    except Exception as e:
        self.display.configure(state="normal")
        self.display.delete(0, tk.END)
        self.display.insert(0, "錯(cuò)誤")
        self.display.configure(state="readonly")
        self.current_expression = ""
        self.is_new_calculation = True

代碼說明:

  • 使用 Python 內(nèi)置的eval()函數(shù)計(jì)算表達(dá)式
  • 支持 π 和 e 等數(shù)學(xué)常數(shù)
  • 處理浮點(diǎn)數(shù)精度問題,避免顯示過長的小數(shù)
  • 包含異常處理,當(dāng)表達(dá)式錯(cuò)誤時(shí)顯示 "錯(cuò)誤"

6.高級數(shù)學(xué)功能

計(jì)算器能實(shí)現(xiàn)多種基本的數(shù)學(xué)運(yùn)算。

def _calculate_sqrt(self):
    # 計(jì)算平方根
    if not self.current_expression or self.is_new_calculation:
        return
    
    try:
        value = float(self.current_expression)
        if value < 0:
            raise ValueError("平方根不能為負(fù)數(shù)")
        
        result = math.sqrt(value)
        
        # 更新歷史記錄和顯示
        ...
        
    except Exception as e:
        self.display.configure(state="normal")
        self.display.delete(0, tk.END)
        self.display.insert(0, "錯(cuò)誤")
        self.display.configure(state="readonly")
        self.current_expression = ""
        self.is_new_calculation = True

def _calculate_trig(self, func):
    # 計(jì)算三角函數(shù)
    if not self.current_expression or self.is_new_calculation:
        return
    
    try:
        value = float(self.current_expression)
        # 假設(shè)輸入是角度,轉(zhuǎn)換為弧度
        radians = math.radians(value)
        
        if func == "sin":
            result = math.sin(radians)
        elif func == "cos":
            result = math.cos(radians)
        elif func == "tan":
            result = math.tan(radians)
        else:
            result = "錯(cuò)誤"
        
        # 更新歷史記錄和顯示
        ...
        
    except Exception as e:
        self.display.configure(state="normal")
        self.display.delete(0, tk.END)
        self.display.insert(0, "錯(cuò)誤")
        self.display.configure(state="readonly")
        self.current_expression = ""
        self.is_new_calculation = True

代碼說明:

  • 平方根計(jì)算:檢查輸入是否為非負(fù)數(shù)
  • 三角函數(shù):將角度轉(zhuǎn)換為弧度進(jìn)行計(jì)算
  • 所有高級功能都有錯(cuò)誤處理機(jī)制

7.用戶輸入處理

def _button_click(self, text):
    # 處理按鈕點(diǎn)擊事件
    if text == "C":
        self._clear_all()
    elif text == "?":
        self._backspace()
    elif text == "=":
        self._calculate()
    elif text == "π":
        self._append_value(str(math.pi))
    elif text == "√":
        self._calculate_sqrt()
    elif text == "^":
        self._append_value("**")
    elif text in ["sin", "cos", "tan"]:
        self._calculate_trig(text)
    elif text == "ln":
        self._calculate_ln()
    elif text == "log":
        self._calculate_log()
    elif text == "1/x":
        self._calculate_reciprocal()
    elif text == "%":
        self._calculate_percentage()
    else:
        self._append_value(text)

def _handle_key_event(self, event):
    # 處理鍵盤事件
    key = event.char
    
    if key.isdigit() or key in "+-*/().":
        self._append_value(key)
    elif key == "\r" or key == "=":
        self._calculate()
    elif key == "\x08":  # Backspace
        self._backspace()
    elif key.lower() == "c":
        self._clear_all()

代碼說明:

  • 按鈕點(diǎn)擊和鍵盤輸入都有相應(yīng)的處理函數(shù)
  • 支持?jǐn)?shù)字、運(yùn)算符和特殊字符輸入
  • 回車鍵和等號都可以觸發(fā)計(jì)算

8.動(dòng)態(tài)字體調(diào)整

輸入框長度是有限的,有時(shí)希望盡量能看清所有輸入的字符,所以做了動(dòng)態(tài)字體調(diào)整。

def _update_display(self):
    # 更新顯示內(nèi)容
    self.display.configure(state="normal")
    self.display.delete(0, tk.END)
    
    # 格式化顯示內(nèi)容
    display_text = self.current_expression
    
    # 檢查表達(dá)式長度,如果太長則縮小字體
    if len(display_text) > 15:
        self.display_font.configure(size=18)
    else:
        self.display_font.configure(size=24)
    
    self.display.insert(0, display_text)
    self.display.configure(state="readonly")

代碼說明:

  • 當(dāng)表達(dá)式長度超過 15 個(gè)字符時(shí),自動(dòng)縮小字體大小
  • 保證長表達(dá)式也能完整顯示在屏幕上

9.程序入口

if __name__ == "__main__":
    root = tk.Tk()
    app = Calculator(root)
    root.mainloop()

代碼說明:

  • 創(chuàng)建主窗口并啟動(dòng)應(yīng)用程序
  • 通過mainloop()方法進(jìn)入事件循環(huán),等待用戶交互

10.功能擴(kuò)展建議

  • 添加記憶功能:增加 M+、M-、MR、MC 按鈕用于存儲(chǔ)和調(diào)用數(shù)值
  • 支持科學(xué)計(jì)數(shù)法:對于極大或極小的計(jì)算結(jié)果,使用科學(xué)計(jì)數(shù)法顯示
  • 添加進(jìn)制轉(zhuǎn)換:支持二進(jìn)制、八進(jìn)制、十進(jìn)制、十六進(jìn)制之間的轉(zhuǎn)換
  • 增加括號匹配提示:在輸入括號時(shí),用不同顏色提示匹配的括號
  • 歷史記錄擴(kuò)展:保存多條歷史計(jì)算記錄,并支持查看和重復(fù)使用

這個(gè)計(jì)算器已經(jīng)具備了基本和高級的計(jì)算功能,界面友好且易于使用。通過進(jìn)一步擴(kuò)展,可以使其成為更加強(qiáng)大的科學(xué)計(jì)算器。

以上就是基于Python的tkinter庫開發(fā)一個(gè)計(jì)算器的完整代碼的詳細(xì)內(nèi)容,更多關(guān)于Python tkinter計(jì)算器的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 關(guān)于adfuller函數(shù)返回值的參數(shù)說明與記錄

    關(guān)于adfuller函數(shù)返回值的參數(shù)說明與記錄

    這篇文章主要介紹了關(guān)于adfuller函數(shù)返回值的參數(shù)說明與記錄,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Python 異常處理實(shí)例詳解

    Python 異常處理實(shí)例詳解

    python提供了兩個(gè)非常重要的功能(異常處理和斷言(Assertions))來處理python程序在運(yùn)行中出現(xiàn)的異常和錯(cuò)誤,你可以使用該功能來捕捉python程序的異常
    2014-03-03
  • Python自動(dòng)化構(gòu)建工具scons使用入門筆記

    Python自動(dòng)化構(gòu)建工具scons使用入門筆記

    這篇文章主要介紹了Python自動(dòng)化構(gòu)建工具scons使用入門筆記,本文講解了安裝scons、scons常用命令、scons使用示例等內(nèi)容,需要的朋友可以參考下
    2015-03-03
  • Python讀取圖片的方法詳解

    Python讀取圖片的方法詳解

    這篇文章主要為大家詳細(xì)介紹了Python中讀取圖片的實(shí)現(xiàn)方法,文中的示例代碼簡潔易懂,具有一定的參考價(jià)值,需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-08-08
  • 使用Python實(shí)現(xiàn)二終端網(wǎng)絡(luò)可靠度

    使用Python實(shí)現(xiàn)二終端網(wǎng)絡(luò)可靠度

    這里給大家分享的是實(shí)現(xiàn)二終端網(wǎng)絡(luò)可靠度的方法以及使用Python實(shí)現(xiàn)的代碼,有需要的小伙伴可以參考下。
    2021-05-05
  • Python使用json模塊讀取和寫入JSON數(shù)據(jù)

    Python使用json模塊讀取和寫入JSON數(shù)據(jù)

    Python 提供了內(nèi)置的 json 模塊,使得我們可以方便地解析 JSON 數(shù)據(jù)(讀?。┖蜕?nbsp;JSON 數(shù)據(jù)(寫入),下面小編就來為大家介紹一下具體的操作步驟吧
    2025-03-03
  • python3獲取文件中url內(nèi)容并下載代碼實(shí)例

    python3獲取文件中url內(nèi)容并下載代碼實(shí)例

    這篇文章主要介紹了python3獲取文件中url內(nèi)容并下載代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • python第三方庫subprocess執(zhí)行cmd同時(shí)輸入密碼獲取參數(shù)

    python第三方庫subprocess執(zhí)行cmd同時(shí)輸入密碼獲取參數(shù)

    本文給大家介紹python subprocess執(zhí)行cmd同時(shí)輸入密碼獲取參數(shù),手動(dòng)輸入cmd命令,本文給大家逐一介紹這個(gè)命令的使用方法,感興趣的朋友跟隨小編一起看看吧
    2024-01-01
  • Python樹的重建實(shí)現(xiàn)示例

    Python樹的重建實(shí)現(xiàn)示例

    樹的重建是一種從給定的遍歷序列中恢復(fù)原樹結(jié)構(gòu)的算法,本文就來介紹一下Python樹的重建實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-11-11
  • Python導(dǎo)入模塊的3種方式小結(jié)

    Python導(dǎo)入模塊的3種方式小結(jié)

    本文主要介紹了Python導(dǎo)入模塊的3種方式小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03

最新評論

苍山县| 朝阳市| 呼伦贝尔市| 谢通门县| 沙田区| 柞水县| 蚌埠市| 琼结县| 集安市| 扬州市| 涪陵区| 彭阳县| 绥滨县| 北票市| 油尖旺区| 永昌县| 西乡县| 股票| 句容市| 宝坻区| 客服| 布尔津县| 新绛县| 罗定市| 桑日县| 冷水江市| 定日县| 泸定县| 齐河县| 青龙| 紫云| 汶上县| 乐安县| 甘肃省| 庆云县| 拜城县| 昭通市| 乐清市| 泸西县| 嵊州市| 道孚县|