会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 47楼

image.png

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

"""测试canvas组件的基本用法,使用面向对象的方式"""
from tkinter import *
import random


class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()

        self.createWidget()

    def createWidget(self):
        self.canvas = Canvas(self, width=300, height=200, bg="green")
        self.canvas.pack()
        # 画一条直线
        line = self.canvas.create_line(10, 10, 30, 20, 40, 50)
        # 画一个矩形
        rect = self.canvas.create_rectangle(50, 50, 100, 100)
        # 画一个椭圆,坐标为椭圆的边界矩形左上角和底部右下角
        oval = self.canvas.create_oval(50, 50, 100, 100)

        global photo
        photo = PhotoImage(file="imgs/logo.gif")
        self.canvas.create_image(150, 170, image=photo)

        Button(self, text="画10个矩形", command=self.draw50Recg).pack(side="left")

    def draw50Recg(self):
        for i in range(0, 10):
            x1 = random.randrange(int(self.canvas["width"])/2)
            y1 = random.randrange(int(self.canvas["height"])/2)
            x2 = x1 + random.randrange(int(self.canvas["width"]/2))
            y2 = y1 + random.randrange(int(self.canvas["height"])/2)
            self.canvas.create_rectangle(x1, y1, x2, y2)




if __name__ == '__main__':
    root = Tk()
    root.geometry("400x240+200+300")
    app = Application(master=root)

    root.mainloop()

老师,我的这个代码为啥会报错

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

老师您好!请问我直接运行我代码,然后在text框里写入一些文本内容后直接点击保存时会报一个错:TypeError: expected str, bytes or os.PathLike object, not NoneType,于是我在保存里加了个判断self.filename是否为空,空的话给它一个保存路径,再运行时才能直接保存:

self.filename = 'F:/Python_pycharm/turtleproject/未命名.txt'

有没有方法能点击直接保存时使他自己选择路径,再进行保存。

代码:

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


class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.filename = None
        self.txt1 = None
        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.newCreateFile)
        menuFile.add_command(label="打开", accelerator="ctrl+o", command=self.openFile)
        menuFile.add_command(label="保存", accelerator="ctrl+s", command=self.saveFile)

        menuEdit.add_command(label="选择背景色", command=self.optionColor)

        root["menu"] = menubar

        self.txt1 = Text(root, width=400, height=300, bg='white')
        self.txt1.pack()


    def newCreateFile(self):
        # 新建文本文档
        self.txt1.delete('1.0', 'end')
        self.filename = asksaveasfilename(title="另存为", initialfile="未命名.txt",
                                      filetypes=[("文本文档", "*.txt")], defaultextension=".txt")
        print(self.filename)
        self.saveFile()

    def openFile(self):
        # 打开文件
        self.txt1.delete('1.0', 'end')
        with askopenfile(title='打开文本文件') as f:
            self.txt1.insert(INSERT, f.read())
            self.filename = f.name
            root.title(self.filename)
            print(f.name)

    def saveFile(self):
        # 保存文件
        if self.filename is not None:
            with open(self.filename, "w") as f:
                c = self.txt1.get(1.0, END)
                f.write(c)
        else:
            self.filename = 'F:/Python_pycharm/turtleproject/未命名.txt'
            c = self.txt1.get(1.0, END)
            with open(self.filename, "w") as f:
                f.write(c)

    def optionColor(self):
        # 选择背景色
        color = askcolor(color='white', title='选择背景色')
        self.txt1.config(bg=color[1])


if __name__ == '__main__':
    root = Tk()
    root.title('新建文本文档.txt  新版记事本')
    root.geometry('800x600+200+100')
    app = Application(master=root)
    root.mainloop()


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

image.png

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

image.png

Python 全系列/第二阶段:Python 深入与提高/坦克大战 58楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 59楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 60楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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