会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 134046个问题

代码:

tkinter *
tkinter.filedialog *  tkinter.colorchooser * tkinter.filedialog *

Application(Frame):

    (master=):
        ().(master)  .master = master
        .textpad = .pack()
        .createWidget()

    ():
        menubar = Menu(root)

        menuFile = Menu(menubar)
        menuEdit = Menu(menubar)
        menuHelp = Menu(menubar)

        menubar.add_cascade(==menuFile)
        menubar.add_cascade(==menuEdit)
        menubar.add_cascade(==menuHelp)

        menuFile.add_command(===.test)
        menuFile.add_command(===.openfile)
        menuFile.add_command(===.savefile)

        menuFile.add_separator()  menuFile.add_command(===.exit)

        root[] = menubar

        .textpad = Text(root==)
        .textpad.pack()

        .contextMenu = Menu(root)
        .contextMenu.add_command(==.openAskColor)

        root.bind(.createContextMenu)

    ():
        .textpad.delete()  (askopenfilename(=)=) f:  .textpad.insert(INSERTf.read())
            .filename = f.name

    ():
        (.filename) f:
            c = .textpad.get(END)
            f.write(c)

    ():
        root.quit()

    ():
        ():
        s1 = askcolor(==)
        root.config(=s1[])

    (event):
        .contextMenu.post(event.x_rootevent.y_root)


__name__ == :
    root = Tk()
    root.geometry()
    root.title()
    app = Application(=root)
    root.mainloop()


控制台:

C:\Users\微软\AppData\Local\Programs\Python\Python37\python.exe C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py

Exception in Tkinter callback

Traceback (most recent call last):

  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__

    return self.func(*args)

  File "C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py", line 62, in openfile

    self.textpad.insert(INSERT, f.read())

  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\codecs.py", line 322, in decode

    (result, consumed) = self._buffer_decode(data, self.errors, final)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 0: invalid start byte


Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2236楼
Python全系列/第二阶段:Python 深入与提高/文件处理 2237楼

#开发一款画图软件
from tkinter import *
from tkinter.filedialog import *
from tkinter.colorchooser import *

win_width=600
win_height=500
class Application(Frame):

    def __init__(self,master=None):
        super().__init__(master)
        self.master = master
        self.x = 0
        self.y = 0
        self.fg = "red"
        self.pack()
        self.createWidget()

    def createWidget(self):

        self.drawpad = Canvas(root,width=win_width,height=win_height*0.9,bg="white")
        self.drawpad.pack()

        btn_star = Button(root,text="strar",name = "star").pack(side="left",padx=10)
        btn_pen = Button(root,text="pen",name="pen").pack(side="left",padx=10)
        btn_rect = Button(root,text="rect",name="rect").pack(side="left",padx=10)
        btn_clear = Button(root,text="clear",name="clear").pack(side="left",padx=10)
        btn_erasor = Button(root,text="erasor",name="erasor").pack(side="left",padx=10)
        btn_line = Button(root, text="line", name="line").pack(side="left", padx=10)
        btn_lineArrow = Button(root, text="lineArrow", name="lineArrow").pack(side="left", padx=10)
        btn_color = Button(root, text="color", name="color").pack(side="left", padx=10)

        btn_pen.bind_class("Button",'<1>',self.eventManager)

    def eventManager(self,event):
        name = event.widget.winfo_name()
        print(name)
        if name=="line":
            self.drawpad.bind("<B1-Motion>",self.myline)


    def myline(self,event):

        self.drawpad.create_line(self.x,self.y,event.x,event.y,fill=self.fg)



if __name__=='__main__':
    root = Tk()
    root.geometry(str(win_width)+"x"+str(win_height))
    app = Application(master=root)
    root.title("简易画图软件")
    root.mainloop()

这里出不来直线咋回事呢

Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2238楼
Python全系列/第二阶段:Python 深入与提高/异常机制 2239楼
Python全系列/第二阶段:Python 深入与提高/坦克大战 2240楼

QQ图片20220509080830.jpg

Python全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2242楼
Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2243楼

老师你好,按照代码打后,画不出直线是怎么回事

"""开发画图软件的菜单
"""

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

#窗口的宽度和高度
win_width=900
win_height=450

class Application(Frame):

    def __init__(self,master=None,bgcolor="#000000"):
        super().__init__(master)
        self.master=master
        self.bgcolor=bgcolor
        self.x=0
        self.y=0
        self.fgcolor="#ff0000"
        self.pack()
        self.createWidget()

    def createWidget(self):
        drawpad= Canvas(root,width=win_width,height=win_height*0.8,bg=self.bgcolor)
        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_clear= Button(root, text="清屏", name="clear")
        btn_clear.pack(side="left", padx="10")
        btn_erasor = Button(root, text="橡皮擦", name="erasor")
        btn_erasor.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)

    def eventManager(self,event):
        name = event.widget.winfo_name()
        print(name)
        if name=="line":
            self.drawpad.bind("B1-Motion>".self.myline)

    def myline(self,event):

        self.drawpad.create_line(self.x,self.y,event.x,event.y,fill=self.fgcolor)

if __name__=='__main__':
    root=Tk()
    root.geometry(str(win_width)+"x"+str(win_height)+"+200+300")
    root.title("百战程序员的画图软件")
    app=Application(master=root)
    root.mainloop()

图片如下

image.png

Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2244楼

问题:txt编码问题,无法正常打开txt。刚开始两次可以,后来加入了文字保存后,再次打开就打不开了;
也尝试了把手动删除txt已添加的文字,结果就一直出现报错。
如何解决?


# coding=gbk
"""开发一个简单的记事本。
  包含:新建、保存、修改文本内容、退出
  包含:各种快捷键的处理
  version 1.0 """

from tkinter import *
from tkinter.filedialog import *  # filedialog 文件对话框
from tkinter.colorchooser import * # colorchooser 颜色选择框
from tkinter.filedialog import *

class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)  # # super()代表的是父类的定义,而不是父类对象

        self.master = master
        self.textpad = None  # textpad 表示Text文本框对象
        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)

        # 添加菜单项
        menuFile.add_command(label="新建", accelerator="ctrl+n", command=self.test)
        menuFile.add_command(label="打开", accelerator="ctrl+0", 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

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

        # 创建快捷菜单(上下文菜单)
        self.contextMenu = Menu(root)
        self.contextMenu.add_command(label="背景颜色", command=self.openAskColor)

        # 为右键绑定事件
        root.bind("<Button-3>", self.createContextMenu)

    def openfile(self):
        self.textpad.delete('1.0', 'end')  # 先把 Text 控件中的内容清空
        with open(askopenfilename(title="opentxt"), encoding="utf-8") as f:  # 打开askopenfilename的固定用法,和编码
            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="选择背景色")
        root.config(bg=s1[1])

    def createContextMenu(self, event):
        # 菜单在鼠标右键单击的坐标处显示
        self.contextMenu.post(event.x_root, event.y_root)


if __name__ == '__main__':
    root = Tk()
    root.geometry("450x300+200+300")
    root.title("简易记事本")
    app = Application(master=root)
    root.mainloop()
    
    
    
控制台:
C:\Users\微软\AppData\Local\Programs\Python\Python37\python.exe C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/微软/pycharm_execrise/pythonProject/GUI/note.py", line 62, in openfile
    self.textpad.insert(INSERT, f.read())
  File "C:\Users\微软\AppData\Local\Programs\Python\Python37\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 0: invalid start byte

Process finished with exit code 0

Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2245楼
Python全系列/第二阶段:Python 深入与提高/坦克大战 2246楼
Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2247楼

from tkinter import *
from tkinter import messagebox
import random

win_width=450
win_height=300
class Application(Frame):
    def __init__(self,master):
        super().__init__(master)
        self.master = master
        self.pack()
        # label组建:小姐姐真漂亮,我喜欢你,图片
        self.label01 = Label(root, text="小姐姐真漂亮,我喜欢你\n做我女朋友好吗?"
                             , font=("KaiTi", 17), width=27, height=2, fg="red")
        self.label01.place(x=0, y=0)
        global photo
        photo = PhotoImage(file="e:/python图片/AKAKA.gif")
        self.label02 = Label(root, image=photo)
        self.label02.place(x=200, y=60)

        # 设置按钮好哒、不愿意
        self.but01 = Button(root, text="好哒", font=("KaiTi", 28), command=self.haoda, activebackground="blue")
        self.but01.place(x=60,y=70)
        self.but02 = Button(root,text="不愿意", font=("KaiTi", 15))
        self.but02.place(x=60,y=170)

        self.but02.bind("<Enter>",self.buyuanyi)

    def buyuanyi(self, event):
        x1 = random.randrange(int(win_width)-50)
        y1 = random.randrange(int(win_height)-50)
        print(x1, y1)
        self.but02.place(x=x1, y=y1)

    def haoda(self):
        messagebox.showinfo("宝贝", "属于我们的甜甜的恋爱开始啦")
        root.destroy()


if __name__ == '__main__':
    root = Tk()
    root.title("I LOVE U")
    root.geometry(str(win_width)+"x"+str(win_height)+"+700+400")
    app = Application(root)
    root.mainloop()

老师,为啥这些地方是root,不能是self,我用了self,就显示不出来了?417236ae20f6b9145b984759fc5ab06.png

Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2248楼

一、代码

#coding=utf-8
"""
开发记事本软件的菜单
"""

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

class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)        # super()代表的是父类的定义,而不是父类对象
        self.master = master
        self.textpad = None             # textpad表示Text文本框对象
        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)

        # 添加菜单项
        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>', self.newfile)
        root.bind('<Control-o>', self.openfile)
        root.bind('<Control-s>', self.savefile)
        root.bind('<Control-q>', self.exit)

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

        # 创建上下菜单
        self.contextMenu = Menu(root)
        self.contextMenu.add_command(label="背景颜色", command=self.AskColor)

        #为右键绑定事件
        root.bind("<Button-3>",self.createContextMenu)

    def newfile(self,event):
        self.textpad.delete(1.0, END)
        self.filename=asksaveasfilename(title="新建",initialfile="未命名.txt",
                                        initialdir='F:/Python/mypro_GUI',
                                        filetype=[('文本文档','*.txt')],defaultextension='.txt')

    def openfile(self,event):
        with askopenfile(title="打开文件",initialdir='F:/Python/mypro_GUI') as f:
            self.textpad.insert(INSERT,f.read())
            self.filename = f.name

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

    def exit(self,event):
        root.quit()

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

    def createContextMenu(self,event):
        # 菜单在鼠标右键单击的坐标处显示
        self.contextMenu.post(event.x_root, event.y_root)


if __name__ == '__main__':
    root = Tk()
    root.geometry("450x300+200+300")
    root.title("百战程序员的简易记事本")
    app = Application(master=root)
    root.mainloop()

二、问题

image.png

老师,为什么我运行生成的.exe文件,点“文件”—“新建”等按钮,都会报上述的错误?

Python全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2249楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637