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

QQ图片20220509080830.jpg

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

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

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

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编程(隐藏) 2224楼

问题: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编程(隐藏) 2225楼
Python 全系列/第二阶段:Python 深入与提高/坦克大战 2226楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2227楼

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编程(隐藏) 2228楼

一、代码

#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编程(隐藏) 2229楼

from tkinter import *  # 导入tkinter里得全部方法
from tkinter import messagebox  # 调用 messaagebox 模块
import random


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

    def createWidget(self):  # 创建组件
        """通过place布局管理实现扑克牌位置控制"""
        self.photos = [PhotoImage(file="venv/11"+str(i+1)+".gif") for i in range(10)]
        self.pukes = [Label(self.master,image=self.photos[i])for i in range(10)]
        for i in range(10):
            self.pukes[i].place(x=10+i*40,y=50)
        self.pukes[0].bind_class("Label","<Button-1>",self.chupai)
    def chupai(self,event):
        print(event.widget.winfo_geometry())
        print(event.widget.winfo_y())
        if event.widget.winfo_y == 50:
            event.widget.place(y=30)
        else:
            event.widget.place(y=50)





if __name__ == '__main__':
    root=Tk()
    root.geometry('800x400+200+300')
    root.title('扑克游戏界面')
    app=Application(master=root)
    root.mainloop()

a23423ffc97e66344a06ebfc7472f6c.png


老师 我这里那些错了吗? 单机牌后 它不动 单机多次坐标都不动 else 中 换成30 单机后 出牌了 却回不来了  帮我看一下咋回事

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2230楼
Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2232楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2233楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2234楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2235楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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