其他分享
首页 > 其他分享> > 分享一个tkinter和虚拟机作品

分享一个tkinter和虚拟机作品

作者:互联网

分享一个tkinter和虚拟机作品


库以及系统要求:
1.python3.6.8
2.pillow
3.Windows10(最好)

下面是一小段虚拟机部分(还有自定义模块没有展示)完整源码见文末链接:

import os
import tkinter as tk
import time
from sys import exit
from PIL import Image, ImageTk

try:
    from .built.SPT import *
    from .built.builtin_func import *
    from .built.tclass import *
except ImportError:
    from built.SPT import *
    from built.builtin_func import *
    from built.tclass import *


def operator(opera, condit):  # 运算符号,指令
    """运算符"""
    if opera not in Avm.oper:
        Avm.senderror("SyntaxError:%s is not defined." % opera)
        return None

    condit1 = run(strip_code(condit[: condit.index(opera)]), strip=False)
    condit2 = run(strip_code(condit[condit.index(opera) + len(opera):]), strip=False)

    # 强制类型转化
    try:
        condit2 = Avm.pytype[type(condit1).__name__](condit2)
    except KeyError:
        # 无法找到对应类型
        Avm.senderror("TypeError:type\"%s\" is not defined.\n" % opera)
    except ValueError:
        # 无法转化类型
        Avm.senderror("TypeError:type\"%s\" couldn\'n be %s.\n" % (condit2, type(condit1).__name__))

    if opera == '==':
        return run(condit1) == run(condit2)
    if opera == '!=':
        return run(condit1) != run(condit2)
    if opera == '>':
        return run(condit1) > run(condit2)
    if opera == '>':
        return run(condit1) < run(condit2)
    if opera == '>':
        return run(condit1) <= run(condit2)
    if opera == '>':
        return run(condit1) >= run(condit2)


class AVM:
    """虚拟机类"""
    # 指令
    codes = []
    # 变量
    addr = {}
    # 运算符
    oper = [
        "==",
        "!=",
        ">=",
        "<=",
        ">",
        "<"
    ]
    typed = {
        "int": aint,
        "string": string,
        "float": afloat
    }
    #类型转化
    pytype = {
        "int": lambda typed: int(typed),
        "str": lambda typed: typed,
        "float": lambda typed: float(typed),
    }
    # 自定义函数
    func_def = {}
    # 程序计数器
    code_num = 0

    def __init__(self):
        self.tree = {
            "if": self.ifif,
            "while": self.con_while,
            "func": self.func,
        }
        self.code = {
            "=": self.valueasas,
        }

        # 内置函数
        self.func_dict = {
            "add": add,
            "exit": self.quit,
            "mul": mul,
            "print": self.printr,
            "div": div,
            "sub": sub,
            "del": self.delvalue,
        }

    def addvalue(self, name, value, vartype):
        # 添加变量
        try:
            fin_value = self.typed[vartype]()
            fin_value.set(value)  # 最终值
            self.addr[name] = (vartype, fin_value)
        except KeyError:
            self.senderror('TypeError:aloud doesn\'t have \"%s\"type.' % vartype)

    def setvalue(self, name, value):
        try:
            self.addr[name][1].set(value)
        except KeyError:
            self.senderror('NameError:%s is not defined' % name)

    def push(self, code):
        self.codes.append(code)

    def leave(self):
        self.window.update()
        re = self.codes[self.code_num]
        self.code_num += 1
        return re

    def valueasas(self, codea):
        codea = strip_code(codea)
        name = strip_code(
            codea[codea.index(" ") + 1: codea.index("=")], del_=" ")
        value = run(strip_code(codea[codea.index("=") + 1:]), strip=False)
        vartype = codea[: codea.index(" ")]

        if value is not None:
            self.addvalue(name, value, vartype)
        else:
            self.senderror("NameError:\'%s\'' is not defined.\n\n" % value)

    def printr(self, strs):
        print_text = ""
        strs = [str(i) for i in strs]
        for i in strs:
            print_text += run(i)
            self.window.update()
        self.text.insert("end", print_text + "\n")

    def delvalue(self, name):
        # 删除变量
        try:
            for i in name:
                del self.addr[i]
        except KeyError as e:
            raise e
            self.senderror("NameError:Could'n del \"%s\"\n\n" % i)

    def file_window(self):
        self.window = tk.Toplevel()
        self.window.title("Aloud")
        self.window.geometry("710x500")
        image = Image.open(os.path.join(os.path.dirname(__file__), "img\\Aloud.png"))
        imagetk = ImageTk.PhotoImage(image)
        image.close()
        self.window.iconphoto(False, imagetk)

        enter_button = tk.Button(self.window, font=(14,), width=2, height=1)
        self.text = tk.Text(
            self.window,
            bg="black",
            fg="white",
            font=("Arial", 14),
            insertbackground="white",
            insertborderwidth=1,
            width=90,
            height=22,
        )
        enter_button.place(x=100, y=0)
        self.text.place(x=0, y=0)

        self.scroll = tk.Scrollbar(self.window)
        # 放到窗口的右侧, 填充Y竖直方向
        self.scroll.pack(side="right", fill="y")
        # 两个控件关联
        self.scroll.config(command=self.text.yview)
        self.text.config(yscrollcommand=self.scroll.set)

    def quit(self, codes):  # 参数是为了接受列表
        self.clear()
        self.window.destroy()


    def ifif(self, condit, codes):
        """条件分支"""
        if run_oper(condit):
            for i in codes:
                run(i)

    def func(self, name, codes):
        self.func_def[name] = codes

    def con_while(self, condit, codes):
        """条件循环"""
        while run_oper(condit):
            for i in codes:
                run(i)

    def senderror(text):
        self.text.insert("end", "Error:Line %s" % (self.code_num+1))
        self.text.insert("end", text)


def getfunc_num(num):
    """获取参数"""
    num_str = num[num.index("(") + 1: num.index(")")]
    numlist = num_str.split(",")  # 返回参数列表
    relist = []
    for i in numlist:
        num = run(i)
        relist.append(num)
    return relist


def block(codes):
    """获取语句块"""
    pass


def run(runc=None, strip=True):
    # 执行引擎
    if runc is None:
        runc = str(Avm.leave())
        if strip:
            runcode = strip_code(runc)
        else:
            runcode = runc
    else:
        runcode = strip_code(str(runc))

    if "#" == runcode[0]:
        run_value(runcode)
        return None

    if "{" == runcode[-1]:
        # 需要找到的}数
        quit_num = 1
        # 指令列表
        tabcodes = []
        while 1:
            # 加入列表的指令
            addcode = Avm.leave()
            tabcodes.append(addcode)
            try:
                # 碰到了新的{
                if addcode[-1] == "{":
                    quit_num += 1
                if addcode[-1] == "}":
                    quit_num -= 1
                    if quit_num == 0:
                        break
            except IndexError:
                pass

        for i in Avm.tree:
            if i in runcode:
                Avm.tree[i](runcode[runcode.index(
                    "(") + 1: runcode.index(")")], tabcodes)  # 如if后的条件
        return None

    elif ("(" in runcode) and (")" in runcode):
        return run_func(runcode)

    return run_type(runc)


def run_oper(code):
    """运算符表达式"""
    for i in Avm.oper:
        if i in code:
            return operator(i, code)


def run_value(code):
    """变量"""
    for i in Avm.code:
        if i in code:
            Avm.code[i](code[1:])
            break
    return None


def run_type(code):
    """负责数据类型和取出变量值"""
    try:
        return Avm.addr[code][1].value
    except KeyError:
        return ftype(str(code))


def run_func(code):
    """执行函数"""
    function = code[: code.index("(")]  # 函数名
    if function in Avm.func_dict:
        # 内置函数
        num = getfunc_num(code)  # 参数
        return Avm.func_dict[function](num)
    elif function in Avm.func_def:
        # 自定义函数
        for i in Avm.func_def[function]:
            run(i)
    else:
        Avm.senderror("NameError:%s is not defined" % function)


def open_text(oc, path):  # 是不是处理后文件
    # 打开文件
    try:
        avm = open(path, encoding="UTF-8")
    except FileNotFoundError:
        oc.senderror("OpenFileError:Cound'n open'%s'\n" % path)
    else:
        avmr = avm.readlines()
        avmw = []
        for i in avmr:
            writecode = strip_code(i)
            if writecode != "":
                try:
                    if writecode[0:2] != "\\\\":
                        avmw.append(writecode)
                except IndexError:
                    pass
    
        oc.codes = avmw
    

def make_Avm(path):
    global Avm
    Avm = AVM()
    open_text(oc=Avm, path=path)
    Avm.file_window()

    end_code = len(Avm.codes)

    starttime = time.clock()
    while end_code != Avm.code_num:
        run()
    endtime = time.clock()
    Avm.text.insert('end', "Finished in %s seconds" % str(endtime - starttime))
    del Avm

https://pan.baidu.com/s/1jB_1COw8Shkfb3XxrxcQGQ
提取码:1v3a

标签:code,run,虚拟机,Avm,num,tkinter,分享,self,def
来源: https://blog.csdn.net/m0_50003906/article/details/112059311