Python学习笔记-自制类似tkinter的GUI模块

Python学习笔记-自制类似tkinter的GUI模块

import tkinter as tk

# Variables.
END = tk.END


def nothing(*args, **kwargs):
    """Nothing to do. Be called for the garmmar."""
    pass


class Position:
    """Position of widget which is showing."""
    def __init__(self, win, x=None, y=None):
        """:argument win: the window which the widget shows on."""
        self.show(x, y) if x is None and y is None else nothing()
    
    show = lambda x, y, **options: place(x=x, y=y, **options)


class Sign:
    def __init__(self, sign: str):
        self.sign = sign
        self.func = nothing
        self.events = []
    
    def __call__(self, event=tk.Event()):
        return self.func(event)
    
    def connect(self, func):
        f = self.func
        self.func = func
        for e in self.events:
            self.unbind(e)
            self.bind(e, self.func)
        return f
    
    def _bind(self, event):
        self.bind(event, self.func)
        self.events.append(event)
    
    def _unbind(self, event):
        self.unbind(event)
        self.events.pop(self.events.find(event))


class Widget(Position, Sign):
    def color(self, col) -> str:
        """Set the color of the widget.
        Warning: not every widget can be set the color."""
        self.config(fg=col)
        return col
    
    def background(self, col) -> str:
        """Set the color of the background of the widget.
        Warning: not every widget can be set the background color."""
        try:
            self.config(bg=col)
        except Exception:
            self.config(background=col)
        return col


class LineEdit(tk.Entry, Widget):
    """A text edition box with one row."""
    def clear(self):
        self.delete(0, tk.END)
    
    @property
    def text(self):
        return self.get(0, tk.END)
    
    def setText(self, text):
        self.clear()
        self.insert(0, text)
    
    def append(self, text):
        """Insert text in the end of edit."""
        self.insert(tk.END, text)


class TextEdit(tk.Text, Widget):
    """A text edition box with rows"
    def clear(self):
        self._delete(0, 0, tk.END, tk.END)
    
    # def _delete(start_row, start_column, end_row, end_column):
    #     start = '{}{}'.format(start_row, start_column) if startrow
    #      '{}{}'.format(end_row, end_column))
    

class Window(tk.Tk, Sign):
    def __init__(self):
        super(tk.Tk, self).__init__()
        self.title('Window')
    
    def position(x, y):
        self.geometry('+{}+{}'.format(x, y))
    
    def size(width, height):
        self.geometry('{}x{}'.format(width, height))
    
    width = lambda: winfo_screenwidth()  # @property
    height = lambda: winfo_screenheight()
    
    show = lambda n=0: mainloop(n)

设备原因,一次不能写太久,正在努力编写中……

你可能感兴趣的:(笔记)