美文网首页GUI 设计
7.1 tkinter Canvas 的几个例子

7.1 tkinter Canvas 的几个例子

作者: 水之心 | 来源:发表于2020-02-01 14:16 被阅读0次

    先载入必备的包:

    from tkinter import Tk, ttk, PhotoImage, Canvas
    from tkinter import Menu, StringVar, filedialog, Listbox
    

    1 一个可以滚动的画布

    class App(Tk):
        def __init__(self):
            super().__init__()
            self._set_scroll()
            self._create_canvas()
            self._scroll_command()
            self._create_button()
            self.canvas.create_window((0, 0), window=self.frame,
                                      anchor='nw')
            self.layout()
            self.bind("<Configure>", self.resize)
            self.update_idletasks()
            self.minsize(self.winfo_width(), self.winfo_height())
    
        def _set_scroll(self):
            self.scroll_x = ttk.Scrollbar(orient='horizontal')
            self.scroll_y = ttk.Scrollbar(orient='vertical')
    
        def _create_canvas(self):
            self.canvas = Canvas(width=300, height=100,
                                 xscrollcommand=self.scroll_x.set,
                                 yscrollcommand=self.scroll_y.set)
    
        def _scroll_command(self):
            self.scroll_x['command'] = self.canvas.xview
            self.scroll_y['command'] = self.canvas.yview
    
        def _create_button(self):
            self.frame = ttk.Frame(self.canvas)
            self.button = ttk.Button(self.frame, text="载入图片",
                                     command=self.load_image)
    
        def layout(self):
            self.button.grid()
            self.canvas.grid(row=0, column=0, sticky="nswe")
            self.scroll_x.grid(row=1, column=0, sticky="we")
            self.scroll_y.grid(row=0, column=1, sticky="ns")
            self.rowconfigure(0, weight=1)
            self.columnconfigure(0, weight=1)
    
        def resize(self, event):
            region = self.canvas.bbox('all')
            self.canvas.configure(scrollregion=region)
    
        def load_image(self):
            self.button.destroy()
            self.image = PhotoImage(file="python.gif")
            ttk.Label(self.frame, image=self.image).grid()
    
    
    if __name__ == "__main__":
        app = App()
        app.mainloop()
    

    create_window 方法将框架添加到可滚动画布。第一个参数是放置与窗口选项一起传递的小部件的位置。由于 Canvas 小控件的 x 轴和 y 轴从左上角开始,因此我们将框架置于 (0,0) 位置,并且还将其与该角对齐,并带有 anchor='nw'。当主窗口调整大小时,绑定到 <Configure> 事件将帮助我们正确重新配置画布。为了获得容器的实际大小,我们必须强制几何管理器通过调用update_idletasks 来绘制所有子小部件。此方法在所有小部件类中都可用,并强制 Tkinter 处理所有挂起的空闲事件,如重新绘制和几何重新计算。要轻松重新计算,可以使用 bbox 方法与 all 常数。这将返回整个"canvas"微件的边界框。

    效果图:

    图1 提供载入图片的按钮

    点击按钮将销毁按钮并载入图片,可以使用滑块查看图片:

    图2 点击按钮载入图片

    2 显示鼠标的坐标

    class App(Tk):
        def __init__(self):
            super().__init__()
            self.title("canvas 基础")
    
            self.canvas = Canvas(bg="white")
            self.label = ttk.Label()
            self.canvas.bind("<Motion>", self.mouse_motion)
            self.canvas.grid()
            self.label.grid()
    
        def mouse_motion(self, event):
            self.label['text'] = f"鼠标位置: ({event.x}, {event.y})"
    
    
    if __name__ == "__main__":
        app = App()
        app.mainloop()
    

    效果图:

    图2 显示鼠标的位置

    3 画线

    class LineForm(ttk.LabelFrame):
        arrows = ('none', 'first', 'last', 'both')
        colors = ("black", "red", "blue", "green")
    
        def __init__(self, master=None, **kw):
            super().__init__(master, text="线条的选择", **kw)
            self.create_var()
            self.set_arrow()
            self.set_color()
            self.set_line()
            self.layout()
            self.arrow.set(self.arrows[0])
            self.color.set(self.colors[0])
            self.line_width.set(1)
    
        def create_var(self):
            self.arrow = StringVar()
            self.color = StringVar()
    
        def set_arrow(self):
            self.arrow_label = ttk.Label(self, text="Arrow style")
            self.arrow_option = ttk.OptionMenu(self, self.arrow, *self.arrows)
    
        def set_color(self):
            self.color_label = ttk.Label(self, text="Fill color")
            self.color_option = ttk.OptionMenu(self, self.color, *self.colors)
    
        def set_line(self):
            self.line_width_label = ttk.Label(self, text="Line width")
            self.line_width = ttk.Spinbox(self, from_=1, to=5, width=5)
    
        def layout(self):
            self.arrow_label.grid(sticky='w', row=0, column=0)
            self.arrow_option.grid(row=0, column=1, pady=10)
            self.color_label.grid(sticky='w', row=1, column=0)
            self.color_option.grid(row=1, column=1, pady=10)
            self.line_width_label.grid(sticky='w', row=2, column=0)
            self.line_width.grid(row=2, column=1, pady=10)
    
        def get_value(self, var_name):
            if var_name == 'arrow':
                return self.arrow.get()
            elif var_name == 'color':
                return self.color.get()
            elif var_name == 'line_width':
                return int(self.line_width.get())
    
    
    class App(Tk):
        def __init__(self):
            super().__init__()
            self.title("Basic canvas")
            self.line_start = None
            self.form = LineForm()
            self.canvas = Canvas(bg="white")
            self.canvas.bind("<Button-1>", self.draw)
    
            self.form.grid(row=0, column=0, padx=10, pady=10)
            self.canvas.grid(row=0, column=1)
    
        def draw(self, event):
            x, y = event.x, event.y
            if not self.line_start:
                self.line_start = (x, y)
            else:
                x_origin, y_origin = self.line_start
                self.line_start = None
                line = (x_origin, y_origin, x, y)
                arrow, color, width = [self.form.get_value(name)
                                       for name in ('arrow', 'color', 'line_width')]
                self.canvas.create_line(*line, arrow=arrow,
                                        fill=color, width=width)
    
    
    if __name__ == "__main__":
        app = App()
        app.mainloop()
    

    显示效果:

    图3 不同格式的线

    4 画出文本

    class App(Tk):
        def __init__(self):
            super().__init__()
            self.title("Canvas text items")
            self.geometry("300x100")
    
            self.var = StringVar()
            self.entry = ttk.Entry(self, textvariable=self.var)
            self.canvas = Canvas(self, bg="white")
    
            self.entry.pack(pady=5)
            self.canvas.pack()
            self.update()
    
            w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
            options = {"font": "courier", "fill": "blue",
                       "activefill": "red"}
            self.text_id = self.canvas.create_text((w/2, h/2), **options)
            self.var.trace("w", self.write_text)
    
        def write_text(self, *args):
            self.canvas.itemconfig(self.text_id, text=self.var.get())
    
    
    if __name__ == "__main__":
        app = App()
        app.mainloop()
    
    图4 画出文本

    画出不同的形状

    class App(Tk):
        shapes = ("rectangle", "oval", "arc")
    
        def __init__(self):
            super().__init__()
            self.title("Drawing standard items")
            style = ttk.Style()
            style.map("C.TButton",
                      foreground=[('pressed', 'red'), ('active', 'blue')],
                      background=[('pressed', '!disabled', 'black'),
                                  ('active', 'white')],
                      relief=[('pressed', '!disabled', 'sunken')]
                      )
    
            self.start = None
            self.shape = None
            self.canvas = Canvas(self, bg="white")
            frame = ttk.Frame(self)
            for shape in self.shapes:
                btn = ttk.Button(frame, text=shape.capitalize(), style="C.TButton")
                btn.config(command=partial(self.set_selection, shape))
                btn.pack(side='left', expand=True, fill='both')
    
            self.canvas.bind("<Button-1>", self.draw_item)
            self.canvas.pack()
            frame.pack(fill='both')
    
        def set_selection(self, shape):
            self.shape = shape
    
        def draw_item(self, event):
            x, y = event.x, event.y
            if not self.start:
                self.start = (x, y)
            else:
                x_origin, y_origin = self.start
                self.start = None
                bbox = (x_origin, y_origin, x, y)
                if self.shape == "rectangle":
                    self.canvas.create_rectangle(*bbox, fill="blue",
                                                 activefill="yellow")
                elif self.shape == "oval":
                    self.canvas.create_oval(*bbox, fill="red",
                                            activefill="yellow")
                elif self.shape == "arc":
                    self.canvas.create_arc(*bbox, fill="green",
                                           activefill="yellow")
    
    
    if __name__ == "__main__":
        app = App()
        app.mainloop()
    
    图5 点击不同按钮画不同的图形

    设置图形可用鼠标隐藏的操作

    root = Tk()
    canvas = Canvas(root)
    canvas.create_rectangle(10, 10, 200, 200, fill='red', tags='rect')
    canvas.create_rectangle(100, 100, 300, 300, fill='blue', tags='rect1')
    
    def set_hidden(event):
        canvas.itemconfigure('rect1', state = 'hidden')
        
    canvas.tag_bind('rect1', '<1>', set_hidden)
    canvas.grid()
    root.mainloop()
    

    当您使用鼠标左键将会把蓝色的矩形隐藏。

    相关文章

      网友评论

        本文标题:7.1 tkinter Canvas 的几个例子

        本文链接:https://www.haomeiwen.com/subject/jnxxxhtx.html