文本计算器 直接上代码: ``` # coding:utf-8 #!/opt/homebrew/bin/python3.9 from __future__ import division import time import sys from math import * import logging as log python_version = sys.version_info.major if python_version == 3: import tkinter as tk elif python_version == 2: import Tkinter as tk class StrCalc(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent scroll_bar = tk.Scrollbar(root) text_box = tk.Text(root, height=4, bg="white", foreground='black', font=("Helvetica", 18), insertborderwidth=3, insertbackground='black') scroll_bar.pack(side=tk.RIGHT, fill=tk.Y) text_box.pack(side=tk.LEFT, fill=tk.Y) scroll_bar.config(command=text_box.yview) text_box.config(yscrollcommand=scroll_bar.set) self.MainText = text_box parent.bind("", self.calc) self.MainText.pack() def calc(self, event): current_line = self.MainText.index(tk.INSERT) line_text = self.MainText.get("{}".format( float(current_line) - 1), "{}".format(float(current_line))) # messagebox.showinfo("Say Hello", line_text) if line_text.strip() == "clean": self.MainText.delete('1.0', tk.END) return result = StrCalc.calc_str(line_text) try: result = "{:.4f}".format(result) except: pass log.debug("calc result is %s" % result) self.MainText.insert("{}".format(float(current_line)), "%s\n" % result) @staticmethod def calc_str(input_str): try: if input_str.strip() == "": return "" input_str = input_str.strip() if StrCalc.is_int(input_str) and (len(input_str) == 10 or len(input_str) == 13): if len(input_str) == 13: input_str = input_str[0:10] time_local = time.localtime(int(input_str)) # 转换成新的时间格式(2016-05-05 20:28:54) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) return dt result = eval(input_str) log.debug("calc_str result {}".format(result)) return result except Exception as errors: return "".join((input_str, str(errors))) @staticmethod def is_int(val): try: _ = int(val) return True except Exception as e: return False if __name__ == "__main__": root = tk.Tk() root.attributes('-topmost', True) root.title(u"文本计算器-超级大猪") root.geometry("600x400") main = StrCalc(root) main.pack(sid="top", fill="both", expand=True) root.mainloop() ``` 来自 大脸猫 写于 2017-05-06 10:39 -- 更新于2022-08-30 16:03 -- 0 条评论