原创

基于tkinter的gui编程基础学习笔记


基于tkinter的gui编程基础学习笔记

知识点代码,上传百度网盘
项目一:记事本
项目二:画图软件

记事本

from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import *
from tkinter.colorchooser import *


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)  # super()代表父类定义
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        # 创建主菜单栏
        menubar = Menu(root)

        # 创建子菜单
        menuFile = Menu(menubar)
        menuEdit = Menu(menubar)
        menuHelp = Menu(menubar)

        # 子菜单加入主菜单
        menubar.add_cascade(label='文件(F)', menu=menuFile)
        menubar.add_cascade(label='编辑(E)', menu=menuEdit)
        menubar.add_cascade(label='帮助(H)', menu=menuHelp)

        # 添加菜单项 accelerator(加速器,快捷键)
        menuFile.add_command(label='新建', accelerator='ctrl+n', command=self.newfile)
        menuFile.add_command(label='打开', accelerator='ctrl+o', command=self.openfile)
        menuFile.add_command(label='保存', accelerator='ctrl+s', command=self.savefile)
        menuFile.add_separator()  # 添加分割线
        menuFile.add_command(label='退出', accelerator='ctrl+q', command=self.exit)

        # 主菜单栏加到根窗口
        root['menu'] = menubar

        # 增加快捷键事件
        root.bind('<Control-n>',lambda event:self.newfile())
        root.bind('<Control-o>',lambda event:self.openfile())
        root.bind('<Control-s>',lambda event:self.savefile())
        root.bind('<Control-q>',lambda event:self.exit())


        # 文本编辑区
        self.textpad = Text(root, width=70, height=22)
        self.textpad.pack()

        # 创建上下文菜单,右键单击出现的菜单
        self.contextMenu = Menu(root)
        self.contextMenu.add_command(label='背景颜色', command=self.openAskColor)

        root.bind('<Button-3>', self.createContextMenu)

    def newfile(self):
        self.filename = asksaveasfilename(title='另存为', initialfile='未命名.txt', filetypes=[('文本文档', '.txt')],
                                          defaultextension='.txt')
        self.savefile()

    def openfile(self):
        self.textpad.delete(1.0, END)  # 清空text
        with askopenfile(title='打开文本文件', mode='r') as f:
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name

    def savefile(self):
        with open(self.filename, 'w')as f:
            c = self.textpad.get(1.0, END)
            f.write(c)

    def exit(self):
        root.quit()

    def test(self):
        pass

    def openAskColor(self):
        s1 = askcolor(color='red',title='选择背景颜色')
        self.textpad.config(bg=s1[1])

    # 在鼠标位置显示菜单
    def createContextMenu(self, event):
        self.contextMenu.post(event.x_root, event.y_root)


if __name__ == '__main__':
    root = Tk()
    root.title('面相对象方法')
    root.geometry('500x300+500+300')
    app = Application(master=root)
    root.mainloop()

画图软件

from tkinter.filedialog import *
from tkinter.colorchooser import *

win_width = 900
win_height = 450


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)  # super()代表父类定义
        self.master = master
        self.bgcolor = '#000000'
        self.x = 0
        self.y = 0
        self.fgcolor = '#ff0000'
        self.lastDraw = 0  # 表示最后绘制的图形id
        self.startDrawFlag = False  # 是否第一次画
        self.pack()
        self.createWidget()

    def createWidget(self):
        # 创建绘图区
        self.drawpad = Canvas(root, width=win_width, height=win_height * 0.9, bg=self.bgcolor)
        self.drawpad.pack()

        # 创建按钮
        btn_start = Button(root, text='开始', name='start')
        btn_start.pack(side='left', padx=10)
        btn_pen = Button(root, text='画笔', name='pen')
        btn_pen.pack(side='left', padx=10)
        btn_rect = Button(root, text='矩形', name='rect')
        btn_rect.pack(side='left', padx=10)
        btn_oval = Button(root, text='圆形', name='oval')
        btn_oval.pack(side='left', padx=10)
        btn_clear = Button(root, text='清屏', name='clear')
        btn_clear.pack(side='left', padx=10)
        btn_earsor = Button(root, text='橡皮擦', name='erasor')
        btn_earsor.pack(side='left', padx=10)
        btn_line = Button(root, text='直线', name='line')
        btn_line.pack(side='left', padx=10)
        btn_lineArrow = Button(root, text='箭头直线', name='lineArrow')
        btn_lineArrow.pack(side='left', padx=10)
        btn_color = Button(root, text='颜色', name='color')
        btn_color.pack(side='left', padx=10)

        # 事件处理
        btn_pen.bind_class('Button', '<1>', self.eventManager)
        self.drawpad.bind('<ButtonRelease-1>', self.stopDraw)

        # 快捷键
        root.bind('<KeyPress-r>', self.kuaijiejian)
        root.bind('<KeyPress-g>', self.kuaijiejian)
        root.bind('<KeyPress-y>', self.kuaijiejian)

    def eventManager(self, event):
        name = event.widget.winfo_name()
        print(name)
        if name == 'line':
            self.drawpad.bind('<B1-Motion>', self.myline)
        elif name == 'lineArrow':
            self.drawpad.bind('<B1-Motion>', self.mylineArrow)
        elif name == 'rect':
            self.drawpad.bind('<B1-Motion>', self.myRect)
        elif name == 'oval':
            self.drawpad.bind('<B1-Motion>', self.myOval)
        elif name == 'pen':
            self.drawpad.bind('<B1-Motion>', self.myPen)
        elif name == 'erasor':
            self.drawpad.bind('<B1-Motion>', self.myErasor)
        elif name == 'clear':
            self.drawpad.delete('all')
        elif name == 'color':
            c = askcolor(color=self.fgcolor, title='选择画笔颜色')
            self.fgcolor = c[1]

    def stopDraw(self, event):
        self.startDrawFlag = False
        self.lastDraw = 0

    def myline(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)

    def mylineArrow(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, arrow=LAST, fill=self.fgcolor)

    def myRect(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_rectangle(self.x, self.y, event.x, event.y, outline=self.fgcolor)

    def myOval(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_oval(self.x, self.y, event.x, event.y, outline=self.fgcolor)

    def myPen(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)
        self.x = event.x
        self.y = event.y

    def myErasor(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.drawpad.create_rectangle(event.x - 10, event.y - 10, event.x + 10, event.y + 10, fill=self.bgcolor)
        self.x = event.x
        self.y = event.y

    def kuaijiejian(self, event):
        print(event.char)
        if event.char == 'r':
            self.fgcolor = '#ff0000'
        if event.char == 'g':
            self.fgcolor = '#00ff00'
        if event.char == 'y':
            self.fgcolor = '#ffff00'


if __name__ == '__main__':
    root = Tk()
    root.title('画图软件项目')
    root.geometry(str(win_width) + 'x' + str(win_height) + '+300+180')
    app = Application(master=root)
    root.mainloop()

``````python
from tkinter.filedialog import *
from tkinter.colorchooser import *

win_width = 900
win_height = 450


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)  # super()代表父类定义
        self.master = master
        self.bgcolor = '#000000'
        self.x = 0
        self.y = 0
        self.fgcolor = '#ff0000'
        self.lastDraw = 0  # 表示最后绘制的图形id
        self.startDrawFlag = False  # 是否第一次画
        self.pack()
        self.createWidget()

    def createWidget(self):
        # 创建绘图区
        self.drawpad = Canvas(root, width=win_width, height=win_height * 0.9, bg=self.bgcolor)
        self.drawpad.pack()

        # 创建按钮
        btn_start = Button(root, text='开始', name='start')
        btn_start.pack(side='left', padx=10)
        btn_pen = Button(root, text='画笔', name='pen')
        btn_pen.pack(side='left', padx=10)
        btn_rect = Button(root, text='矩形', name='rect')
        btn_rect.pack(side='left', padx=10)
        btn_oval = Button(root, text='圆形', name='oval')
        btn_oval.pack(side='left', padx=10)
        btn_clear = Button(root, text='清屏', name='clear')
        btn_clear.pack(side='left', padx=10)
        btn_earsor = Button(root, text='橡皮擦', name='erasor')
        btn_earsor.pack(side='left', padx=10)
        btn_line = Button(root, text='直线', name='line')
        btn_line.pack(side='left', padx=10)
        btn_lineArrow = Button(root, text='箭头直线', name='lineArrow')
        btn_lineArrow.pack(side='left', padx=10)
        btn_color = Button(root, text='颜色', name='color')
        btn_color.pack(side='left', padx=10)

        # 事件处理
        btn_pen.bind_class('Button', '<1>', self.eventManager)
        self.drawpad.bind('<ButtonRelease-1>', self.stopDraw)

        # 快捷键
        root.bind('<KeyPress-r>', self.kuaijiejian)
        root.bind('<KeyPress-g>', self.kuaijiejian)
        root.bind('<KeyPress-y>', self.kuaijiejian)

    def eventManager(self, event):
        name = event.widget.winfo_name()
        print(name)
        if name == 'line':
            self.drawpad.bind('<B1-Motion>', self.myline)
        elif name == 'lineArrow':
            self.drawpad.bind('<B1-Motion>', self.mylineArrow)
        elif name == 'rect':
            self.drawpad.bind('<B1-Motion>', self.myRect)
        elif name == 'oval':
            self.drawpad.bind('<B1-Motion>', self.myOval)
        elif name == 'pen':
            self.drawpad.bind('<B1-Motion>', self.myPen)
        elif name == 'erasor':
            self.drawpad.bind('<B1-Motion>', self.myErasor)
        elif name == 'clear':
            self.drawpad.delete('all')
        elif name == 'color':
            c = askcolor(color=self.fgcolor, title='选择画笔颜色')
            self.fgcolor = c[1]

    def stopDraw(self, event):
        self.startDrawFlag = False
        self.lastDraw = 0

    def myline(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)

    def mylineArrow(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_line(self.x, self.y, event.x, event.y, arrow=LAST, fill=self.fgcolor)

    def myRect(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_rectangle(self.x, self.y, event.x, event.y, outline=self.fgcolor)

    def myOval(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.lastDraw = self.drawpad.create_oval(self.x, self.y, event.x, event.y, outline=self.fgcolor)

    def myPen(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.drawpad.create_line(self.x, self.y, event.x, event.y, fill=self.fgcolor)
        self.x = event.x
        self.y = event.y

    def myErasor(self, event):
        self.drawpad.delete(self.lastDraw)
        if not self.startDrawFlag:
            self.startDrawFlag = True
            self.x = event.x
            self.y = event.y
        # self.lastDraw 表示最后绘制的图形id
        self.drawpad.create_rectangle(event.x - 10, event.y - 10, event.x + 10, event.y + 10, fill=self.bgcolor)
        self.x = event.x
        self.y = event.y

    def kuaijiejian(self, event):
        print(event.char)
        if event.char == 'r':
            self.fgcolor = '#ff0000'
        if event.char == 'g':
            self.fgcolor = '#00ff00'
        if event.char == 'y':
            self.fgcolor = '#ffff00'


if __name__ == '__main__':
    root = Tk()
    root.title('画图软件项目')
    root.geometry(str(win_width) + 'x' + str(win_height) + '+300+180')
    app = Application(master=root)
    root.mainloop()

学习代码

链接:https://pan.baidu.com/s/1WC5Se6MOMCfJSyDGMmBJrw

提取码:3x1y

python
tkinter
  • 作者:曾强(联系作者)
  • 发表时间:2020-03-17 10:12
  • 版权声明:自由转载-非商用-非衍生-保持署名
  • 转载声明:转载时请注明出处:www.zengqiang.club
  • 注:如果文章有错误,望请评论指出,谢谢;如果看了文章还有不明白的地方,欢迎进群与我交流。
  • 评论