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

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

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


class Application(Frame):

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

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

        # 创建主菜单三个
        menuFile = Menu(menubar)
        menuEdit = Menu(menubar)
        menuHelp = Menu(menubar)

        # 将三个主菜单加入主菜单栏中
        menubar.add_cascade(text="文件[F]", menu=menuFile)
        menubar.add_cascade(text="编辑[E]", menu=menuEdit)
        menubar.add_cascade(text="帮助[H]", menu=menuHelp)

        # 为文件[F]增加子菜单项
        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=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 newfile(self):
        self.textpad.delete("1.0", "end")  # 把text中的所有的内容清空
        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="打开文本文件") as f:
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name

    def savefile(self):
        self.textpad.delete("1.0", "end")  # 把text中的所有的内容清空
        with open(self.filename, "w") as f:
            c = self.textpad.get(1.0, END)
            f.write(c)

    def exit(self):
        root.quit()

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

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


if __name__ == '__main__':
    root = Tk()
    root.geometry("500x400+200+300")
    root.title("私用记事本")
    app = Application(master=root)
    root.mainloop()

屏幕截图 2021-03-29 190337.png

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 843楼
Python 全系列/第二阶段:Python 深入与提高/坦克大战 845楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 848楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 849楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 850楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 851楼
Python 全系列/第二阶段:Python 深入与提高/模块 853楼

image.png

Python 全系列/第二阶段:Python 深入与提高/文件处理 854楼

"""这是一个经典的gui程序的写法,使用面向对象的方式"""from tkinter import *from tkinter import messageboxclass Application(Frame): """一个经典的gui程序""" # 定义构造器 def __init__(self,master=None): # 要将父类的构造器定义进来,不然不会被继承(application继承了frame 但他不会自动调用frame的构造器) # super()代表父类的定义,而不是父类对象 super().__init__(master) self.master = master self.pack() #调用布局管理器,将组件显示在窗口 self.creatWidget() def creatWidget(self): """通过grid布局实现计算器的界面""" # 将文本全部存到元组或列表中,可以存到元组中,因为这些文本是不变的 # 数字可以加引号,也可以不加 btnText = (('MC','M+','M-','MR'), ('C','±','÷','*'), ('7','8','9','-'), ('4','5','6','+'), (1,2,3,'='), (0,'.')) Entry(self).grid(row=0,column=0,columnspan=4,pady=10) # rindex 行的索引 r 这一行 # cindex 对元组再次循环 才能取到一个一个的元素 for rindex,r in enumerate(btnText): for cindex,c in enumerate(r): # 处理等号和零占格的问题 if c == '=': Button(self, text=c, width=2).grid(row=rindex + 1, column=cindex, rowspan=2,sticky=EW) elif c == 0: Button(self, text=c, width=2).grid(row=rindex + 1, column=cindex, columnspan=2,sticky=EW) elif c == '.': # 0占了两列,.就往后移一列 Button(self, text=c, width=2).grid(row=rindex + 1, column=cindex+1, rowspan=2, sticky=EW) else: Button(self,text=c,width=2).grid(row=rindex+1,column=cindex,sticky=EW)if __name__ == '__main__': root = Tk() root.geometry("200x300+200+300") #长400 x 高100 距左边界200 上边界300 root.title("一个经典gui") #定义label时可以删掉 app = Application(master=root) root.mainloop()老师,为啥我的等号没办法跨越两行?

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

课程分类

百战程序员微信公众号

百战程序员微信小程序

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