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

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

from tkinter.filedialog import *
from tkinter import *
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.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

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

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

  def openfile(self):
      self.textpad.delete("1.0", "end")
      with askopenfile(title="打开文本文件") 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)

          # 获得目前text里面从1行0列到最后END里所有的内容


  def exit(self):
      root.quit()


  def test(self):
    pass

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

老师我在尝试做新建按钮程序的时候,每次在新建完一个文本后,都会报错。报错内容为:

 File "C:\Program Files\python\lib\tkinter\__init__.py", line 1921, in __call__

    return self.func(*args)

  File "C:\Users\wangx\PycharmProjects\gui\notebook.py", line 53, in newfile

    self.savefile()

  File "C:\Users\wangx\PycharmProjects\gui\notebook.py", line 62, in savefile

    with open(self.filename, "w") as f:

TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper


新建完之后,本地是有新建的文本的,也可以通过phthon打开,然后编辑再保存再打开。但是就是不能像老师视频里那样操作,直接新建后再新建的对话框里面输入内容后,然后点击保存再打开。每次新建完都会报上面的错误。

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

"""开发记事本软件的菜单"""

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.test)
        menuFile.add_command(label='打开', accelerator='ctrl+o', command=self.openfile)
        menuFile.add_command(label='保存', accelerator='ctrl+s', command=self.test)
        menuFile.add_separator()  # 添加分割线
        menuFile.add_command(label='退出', accelerator='ctrl+q', command=self.test)

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

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

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

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

    def openfile(self):
        self.textpad.delete("1.0", "end")  # 把text控件中所有的内容清空
        with askopenfile(title="打开文本文件") as f:
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name
        # try:
        #     # 以utf-8编码打开
        #     with open(askopenfilename()) as f:
        #         self.textpad.insert(INSERT, f.read())
        #         self.filename = f.name
        #         print(f.read())
        # except UnicodeDecodeError:
        #     # 以GBK编码打开
        #     with open(askopenfilename()) as f:
        #         print(f.read())

    def test(self):
        pass

    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

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

1.png

画红圈的这块写他的意义何在,不写也能正常运行代码啊

Python 全系列/第二阶段:Python 深入与提高/异常机制 2054楼

运行代码:

from tkinter import *
from PIL import Image, ImageTk
import random


class Application(Frame):

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

    def createWidget(self):
        self.btn1 = Button(self, text='送', command=self.song)
        self.btn1.pack()
        self.btnquit = Button(self, text='退出', command=root.destroy, bg='red', fg='blue')
        self.btnquit.pack()

    def get_picture(self, filepath):
        img = Image.open(filepath)
        pic = ImageTk.PhotoImage(img)
        return pic

    def set_picture(self):
        flowers = self.get_picture('flower1.jpg')
        money = self.get_picture('money1.jpg')
        shit = self.get_picture('shit1.jpg')
        book = self.get_picture('book1.jpg')
        phone = self.get_picture('phone1.jpg')
        clothes = self.get_picture('clothes1.jpg')
        song_list = [flowers, money, shit, book, phone, clothes]
        number = random.randint(0, 5)
        return song_list[number]

    def song(self):
        global photo
        photo = self.set_picture()
        self.labpic = Label(self, image=photo)
        self.labpic.pack()


if __name__ == '__main__':
    root = Tk()
    root.geometry('800x600+200+200')
    root.title('首个tk')
    app = Application(master=root)
    root.mainloop()

运行截图:

image.png

image.png



image.png


点击送第二次的时候图片会在第一个图的下面,点击送第三次的时候就看不到图片了

请问能不能每次点击送的时候图片都在正中间?

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

课程分类

百战程序员微信公众号

百战程序员微信小程序

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