好友
阅读权限 10
听众
最后登录 1970-1-1
本帖最后由 sxflzyg 于 2024-7-16 05:09 编辑
1.历史记录中的每个数值双击后直接进到计算器框里面 方便计算 比如123+456=579 双击123 123就到计算器框里了。眼神要好点 别点错了 还有用心校对。
2.历史记录中的每一条计算可以通过右键单击1次变成蓝色 单击2次变绿色 单击3次变紫色 单击4次取消颜色 不敢再多做颜色了怕点的手疼。感觉够用了
3.取消了所有误触或不对的弹窗警告。主打安静。目前没有发现恶性BUG。
4.窗口尺寸 600*600 这个最好不要调,调小了会挤兑,大神的可以优化下调。 窗口初始位500*500 这个起始位自己可以找到下面代码调。
self.geometry("600x600+500+500") # 设置窗口的初始位置和大小
还没学会优化压缩只是在CMD下用下面命令初压了,朋友也睡了,以前压别的能小一半体积。
pyinstaller --onefile --noconsole 2.py
蓝奏云(无优化压缩):https://wwo.lanzouq.com/ifNSd24kty5a
import tkinter as tk
# 将阿拉伯数字转换为中文大写数字的函数
def num_to_chinese(num):
chinese_nums = "零一二三四五六七八九"
chinese_units = ["", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿", "兆", "十兆", "百兆", "千兆", "京", "十京", "百京", "千京", "垓", "十垓", "百垓", "千垓"]
if num == 0:
return chinese_nums[0]
num_str = str(num)
if '.' in num_str:
integer_part, decimal_part = num_str.split('.')
else:
integer_part, decimal_part = num_str, ''
length = len(integer_part)
result = ""
zero_flag = False # 用于处理连续的零
for i in range(length):
digit = int(integer_part)
unit = chinese_units[length - i - 1]
if digit == 0:
zero_flag = True
else:
if zero_flag:
result += chinese_nums[0]
zero_flag = False
result += chinese_nums[digit] + unit
result = result.rstrip(chinese_nums[0])
result = result.replace("零万", "万").replace("零亿", "亿").replace("零兆", "兆").replace("零京", "京").replace("零垓", "垓")
result = result.replace("零零", "零")
if result.startswith("一十"):
result = result[1:]
if decimal_part and int(decimal_part) != 0:
result += "点"
for digit in decimal_part:
result += chinese_nums[int(digit)]
return result
class Calculator(tk.Tk):
def __init__(self):
super().__init__()
self.title("计算器")
self.geometry("600x600+500+500") # 设置窗口的初始位置和大小
self.result_var = tk.StringVar()
self.result_var.trace('w', self.update_chinese_display)
self.chinese_var = tk.StringVar()
self.history = []
self.history_tags = []
self.button_colors = {
'0': 'lightgray', '1': 'lightblue', '2': 'lightgreen', '3': 'lightpink',
'4': 'lightyellow', '5': 'lightcoral', '6': 'lightsalmon', '7': 'lightcyan',
'8': 'lightgoldenrod', '9': 'lightseagreen', '+': 'lightskyblue', '-': 'lightsteelblue',
'*': 'lightgreen', '/': 'lightpink', '=': 'lightgray', '.': 'lightyellow', '清除': 'lightcoral',
'退格': 'lightsalmon', '删除历史记录': 'orange'
}
self.create_widgets()
def create_widgets(self):
# 显示结果的Entry控件
self.result_entry = tk.Entry(self, textvariable=self.result_var, font=('Arial', 24), bd=1, insertwidth=2, width=20, borderwidth=1, relief="flat")
self.result_entry.grid(row=0, column=0, columnspan=5, sticky="we")
# 显示中文大写数字的Entry控件(只读)
self.chinese_entry = tk.Entry(self, textvariable=self.chinese_var, font=('Arial', 14), fg='purple', bd=1, state='readonly', readonlybackground='white', relief="flat")
self.chinese_entry.grid(row=1, column=0, columnspan=5, sticky="we")
# 清除和退格按钮
clear_button = tk.Button(self, text='清除', padx=20, pady=20, font=('Arial', 18), command=self.clear, bg=self.button_colors['清除'])
clear_button.grid(row=2, column=0, columnspan=2, sticky="we")
back_button = tk.Button(self, text='退格', padx=20, pady=20, font=('Arial', 18), command=self.backspace, bg=self.button_colors['退格'])
back_button.grid(row=2, column=2, columnspan=2, sticky="we")
# 删除历史记录按钮
delete_history_button = tk.Button(self, text='删除历史记录', command=self.delete_history, bg=self.button_colors['删除历史记录'], font=('Arial', 12))
delete_history_button.grid(row=2, column=4, padx=5, pady=5, sticky="ne")
# 显示历史记录文本框
self.history_text = tk.Text(self, height=30, width=24, state=tk.DISABLED)
self.history_text.grid(row=3, column=4, rowspan=5, padx=5)
self.history_text.bind("<Double-Button-1>", self.on_history_double_click)
self.history_text.bind("<Button-3>", self.on_history_right_click)
# 定义按钮
buttons = [
('7', '7'), ('8', '8'), ('9', '9'), ('/', '/'),
('4', '4'), ('5', '5'), ('6', '6'), ('*', '*'),
('1', '1'), ('2', '2'), ('3', '3'), ('-', '-'),
('0', '0'), ('.', '.'), ('=', '='), ('+', '+')
]
row_val = 3
col_val = 0
for text, char in buttons:
if char == '=':
btn = tk.Button(self, text=text, padx=20, pady=20, font=('Arial', 18), command=self.evaluate, bg=self.button_colors[char])
else:
btn = tk.Button(self, text=text, padx=20, pady=20, font=('Arial', 18), command=lambda b=char: self.update_expression(b), bg=self.button_colors[char])
btn.grid(row=row_val, column=col_val, sticky="nsew")
col_val += 1
if col_val > 3:
col_val = 0
row_val += 1
for i in range(9):
self.grid_rowconfigure(i, weight=1)
for i in range(5):
self.grid_columnconfigure(i, weight=1)
def update_expression(self, char):
if char == '=':
self.evaluate()
else:
current_text = self.result_var.get()
new_text = current_text + char
self.result_var.set(new_text)
def clear(self):
self.result_var.set("")
def backspace(self):
current_text = self.result_var.get()
new_text = current_text[:-1]
self.result_var.set(new_text)
def evaluate(self):
try:
expression = self.result_var.get()
result = str(eval(expression))
self.result_var.set(result)
self.update_history(expression + " = " + result)
except Exception:
self.result_var.set("")
def update_history(self, entry):
self.history.append(entry)
current_tags = self.history_text.tag_names("end-1c")
if not current_tags:
current_tags = ["default"]
self.history_tags.append(current_tags)
self.display_history()
def display_history(self):
self.history_text.config(state=tk.NORMAL)
self.history_text.delete(1.0, tk.END)
for i, entry in enumerate(self.history):
self.history_text.insert(tk.END, entry + "\n")
for tag in self.history_tags:
self.history_text.tag_add(tag, f"{i + 1}.0", f"{i + 1}.end")
self.history_text.config(state=tk.DISABLED)
def on_history_double_click(self, event):
self.history_text.config(state=tk.NORMAL)
clicked_text_index = self.history_text.index("@%s,%s" % (event.x, event.y))
# 获取点击行的行号和文本
line_number = clicked_text_index.split('.')[0]
line_start = self.history_text.index(f"{line_number}.0")
line_end = self.history_text.index(f"{line_number}.end")
line_text = self.history_text.get(line_start, line_end)
# 通过空格和符号分割行,以找到实际点击的数字/操作符
parts = []
buffer = ''
for char in line_text:
if char in ' =+-*/':
if buffer:
parts.append(buffer)
buffer = ''
parts.append(char)
else:
buffer += char
if buffer:
parts.append(buffer)
# 计算行内字符的位置
char_position = int(clicked_text_index.split('.')[1])
cumulative_length = 0
for part in parts:
cumulative_length += len(part)
if cumulative_length >= char_position:
clicked_word = part.strip()
break
self.update_expression(clicked_word)
self.history_text.config(state=tk.DISABLED)
def on_history_right_click(self, event):
self.history_text.config(state=tk.NORMAL)
clicked_text_index = self.history_text.index("@%s,%s" % (event.x, event.y))
line_start = self.history_text.index("%s linestart" % clicked_text_index)
line_end = self.history_text.index("%s lineend" % clicked_text_index)
current_tags = self.history_text.tag_names(line_start)
if 'blue' in current_tags:
self.history_text.tag_remove('blue', line_start, line_end)
self.history_text.tag_add('green', line_start, line_end)
elif 'green' in current_tags:
self.history_text.tag_remove('green', line_start, line_end)
self.history_text.tag_add('purple', line_start, line_end)
elif 'purple' in current_tags:
self.history_text.tag_remove('purple', line_start, line_end)
else:
self.history_text.tag_add('blue', line_start, line_end)
self.history_text.tag_configure('blue', foreground='blue')
self.history_text.tag_configure('green', foreground='green')
self.history_text.tag_configure('purple', foreground='purple')
self.history_tags[int(line_start.split('.')[0]) - 1] = self.history_text.tag_names(line_start)
self.history_text.config(state=tk.DISABLED)
def delete_history(self):
self.history = []
self.history_tags = []
self.history_text.config(state=tk.NORMAL)
self.history_text.delete(1.0, tk.END)
self.history_text.config(state=tk.DISABLED)
def update_chinese_display(self, *args):
current_text = self.result_var.get()
try:
num = float(current_text)
self.chinese_var.set(num_to_chinese(num))
except ValueError:
self.chinese_var.set("")
if __name__ == "__main__":
try:
calc = Calculator()
calc.mainloop()
except Exception as e:
print("发生错误:", e)
input("按回车键退出...") # 保持窗口打开以查看错误
免费评分
查看全部评分