Python 为什么辅助GUI在主GUI之前打开?

Python 为什么辅助GUI在主GUI之前打开?,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我正在尝试使用python(tkinter)制作GUI记事本 但问题是,辅助GUI窗口打开了,即主窗口记事本之前的列表框 只有当用户单击“窗口”菜单,然后单击“颜色”时,辅助窗口才会打开 窗口菜单有self.listbox.listbx命令,我想只有当用户点击窗口菜单时,该命令才会起作用,我做错了什么 from tkinter import * from tkinter import messagebox as msg from tkinter.filedialog import askopen

我正在尝试使用python(tkinter)制作GUI记事本 但问题是,辅助GUI窗口打开了,即主窗口记事本之前的列表框

只有当用户单击“窗口”菜单,然后单击“颜色”时,辅助窗口才会打开

窗口菜单有self.listbox.listbx
命令,我想只有当用户点击窗口菜单时,该命令才会起作用,我做错了什么

from tkinter import *
from tkinter import messagebox as msg
from tkinter.filedialog import askopenfilename, asksaveasfilename
import os

class Notepad(Tk):

    """Class for notepad """
#  Command for menus-

    def newFile(self):
 
        self.crfile = None
        self.txtarea.delete(1.0, END)

    def saveFile(self):

        if self.crfile == None:
            self.crfile = asksaveasfilename(initialfile="Untitled.txt",
                                            defaultextension=".txt", filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")])
            if self.crfile == "":
                self.crfile = None
            else:
                # Save as new file
                with open(self.crfile, "w") as f:
                    f.write(self.txtarea.get(1.0, END))
                    self.title(os.path.basename(
                        self.crfile + "-  Notepad"))
        else:
            # Save the file
            with open(self.crfile, "w") as f:
                f.write(self.txtarea.get(1.0, END))
                self.title(os.path.basename(
                    self.crfile + "-  Notepad"))

    def openFile(self):

        self.crfile = askopenfilename(defaultextension=".txt", filetypes=[
                                      ("All Files", "*.*"), ("Text Documents", "*.txt")])
        if self.crfile == "":
            self.crfile = None
        else:
            self.title(os.path.basename(self.crfile) +
                       "-" + "Notepad")
            self.txtarea.delete(1.0, END)
            with open(self.crfile, "r") as f:
                self.txtarea.insert(1.0, f.read())

    # commands for edit menu-

    def copy(self):
        self.txtarea.event_generate(("<<Copy>>"))

    def paste(self):
        self.txtarea.event_generate(("<<Paste>>"))

    def cut(self):
        self.txtarea.event_generate(("<<Cut>>"))

    # commands for help menu-

    def About(self):
        msg.showinfo("Notepad -Help",
                     "This is a simple notepad made by ...")

    def menus(self):

        # TODO Menus
        mainmenu = Menu(self, tearoff="0")
        # file menu
        file = Menu(mainmenu, tearoff=0)
        # Creating new file
        file.add_command(label="New", command=self.newFile)
        # Saving the current file
        file.add_command(label="Save", command=self.saveFile)
        # Opening a Pre-Existing file
        file.add_command(label="Open", command=self.openFile)
        file.add_separator()
        file.add_command(label="Exit", command=self.destroy)  # Exit command
        mainmenu.add_cascade(menu=file, label="File")
        self.config(menu=mainmenu)

        # Edit menu---
        edit = Menu(mainmenu, tearoff=0)
        # To cut any part of the Textarea
        edit.add_command(label="Cut", command=self.cut)
        # To copy any part of the Textarea
        edit.add_command(label="Copy", command=self.copy)
        # To paste any cut or copied Text.
        edit.add_command(label="Paste", command=self.paste)
        mainmenu.add_cascade(menu=edit, label="Edit")
        self.config(menu=mainmenu)

        # Help menu---
        helpm = Menu(mainmenu, tearoff=0)
        # Displays about the notepad
        helpm.add_command(label="About", command=self.About)
        mainmenu.add_cascade(menu=helpm, label="Help")
        self.config(menu=mainmenu)

        # Window menu
        win = Menu(mainmenu, tearoff=0)
        win.add_command(label="Colour", command=self.listbox.listbx)
        mainmenu.add_cascade(menu=win, label="Window")
        self.config(menu=mainmenu)

    def textwid(self):

        # TODO Text widget---

        self.txtarea = Text(self)
        self.crfile = None
        self.txtarea.pack(expand=True, fill=BOTH)
        # TODO Scrollbar---
        self.scbar = Scrollbar(self.txtarea)
        self.txtarea.config(yscrollcommand=self.scbar.set)
        self.scbar.config(command=self.txtarea.yview)
        self.scbar.pack(side=RIGHT, fill=BOTH)

    class listbox(Tk):
        
        def listbx(self):
    
    
            self.lbx = Listbox(self)
            colours = ["blue", "red", "yellow",
                        "grey", "green", "light blue", "black"]

            for c in colours:
                self.lbx.insert(END, c)
            self.lbx.pack()
            self.lbx.bind("<<ListboxSelect>>", self.selection)


        def selection(self, event):

            """Selection of colour from the  lisbox above to apply changes"""

            colour = self.lbx.get(ANCHOR)
            msgselect = msg.askokcancel(
                "Window-Colour", "Confirm the colour to apply to the window")
            if msgselect == True:
                root.configure(bg=colour)
                self.destroy()
            else:
                self.destroy()
    root2 = listbox()
    root2.geometry("300x200")
    root2.title("Window-Colour")
    root2.listbx()
    root2.mainloop()
        


if __name__ == "__main__":
    # Basic tkinter startup

    root = Notepad()
    root.geometry("800x700")
    root.title("Notepad-Untitled-1")
    root.menus()
    root.textwid()
    root.wm_iconbitmap("noteicon.ico")
     
   

    root.mainloop()
从tkinter导入*
从tkinter导入消息框作为消息
从tkinter.filedialog导入askopenfilename、asksaveasfilename
导入操作系统
课堂记事本(Tk):
“”“用于记事本的类”“”
#菜单命令-
def新文件(自身):
self.crfile=None
self.txtarea.delete(1.0,结束)
def保存文件(自身):
如果self.crfile==无:
self.crfile=asksaveasfilename(initialfile=“Untitled.txt”,
defaultextension=“.txt”,文件类型=[(“所有文件”,“**”),(“文本文档”,“*.txt”)])
如果self.crfile==“”:
self.crfile=None
其他:
#另存为新文件
打开(self.crfile,“w”)作为f:
f、 写入(self.txtarea.get(1.0,结束))
self.title(os.path.basename(
self.crfile+“-Notepad”))
其他:
#保存文件
打开(self.crfile,“w”)作为f:
f、 写入(self.txtarea.get(1.0,结束))
self.title(os.path.basename(
self.crfile+“-Notepad”))
def openFile(self):
self.crfile=askopenfilename(defaultextension=“.txt”),文件类型=[
(“所有文件”,“**”),(“文本文档”,“*.txt”)])
如果self.crfile==“”:
self.crfile=None
其他:
self.title(os.path.basename(self.crfile)+
“-”+“记事本”)
self.txtarea.delete(1.0,结束)
打开(self.crfile,“r”)作为f:
self.txtarea.insert(1.0,f.read())
#用于编辑菜单的命令-
def副本(自我):
self.txtarea.event_生成((“”)
def粘贴(自):
self.txtarea.event_生成((“”)
def切割(自):
self.txtarea.event_生成((“”)
#帮助菜单命令-
关于(自我)的定义:
msg.showinfo(“记事本-帮助”,
“这是一个简单的记事本,由…”
def菜单(自我):
#待办事项菜单
mainmenu=菜单(self,tearoff=“0”)
#文件菜单
文件=菜单(主菜单,tearoff=0)
#创建新文件
file.add_命令(label=“New”,command=self.newFile)
#保存当前文件
file.add_命令(label=“Save”,command=self.saveFile)
#打开预先存在的文件
file.add_命令(label=“Open”,command=self.openFile)
添加分隔符()
file.add_命令(label=“Exit”,command=self.destroy)#Exit命令
main menu.add_cascade(menu=file,label=“file”)
self.config(menu=main菜单)
#编辑菜单---
编辑=菜单(主菜单,tearoff=0)
#要剪切文本区域的任何部分
编辑.add_命令(label=“Cut”,command=self.Cut)
#复制文本区域的任何部分
编辑.add_命令(label=“Copy”,command=self.Copy)
#粘贴任何剪切或复制的文本。
编辑.add_命令(label=“Paste”,command=self.Paste)
主菜单。添加(菜单=编辑,标签=编辑)
self.config(menu=main菜单)
#帮助菜单---
helpm=菜单(主菜单,tearoff=0)
#显示有关记事本的信息
helpm.add_命令(label=“About”,command=self.About)
main menu.add_cascade(menu=helpm,label=“Help”)
self.config(menu=main菜单)
#窗口菜单
win=菜单(主菜单,TEAROF=0)
win.add_命令(label=“color”,command=self.listbox.listbx)
mainmenu.add_cascade(menu=win,label=“Window”)
self.config(menu=main菜单)
def textwid(自我):
#待办事项文本小部件---
self.txtarea=文本(self)
self.crfile=None
self.txtarea.pack(expand=True,fill=BOTH)
#待办事项滚动条---
self.scbar=滚动条(self.txtarea)
self.txtarea.config(yscrollcommand=self.scbar.set)
self.scbar.config(命令=self.txtarea.yview)
self.scbar.pack(侧面=右侧,填充=两侧)
类列表框(Tk):
def listbx(自身):
self.lbx=列表框(self)
颜色=[“蓝色”、“红色”、“黄色”,
“灰色”、“绿色”、“浅蓝色”、“黑色”]
颜色为c的:
自卸扣插入件(结束,c)
self.lbx.pack()
self.lbx.bind(“,self.selection)
def选择(自身、事件):
“”“从上面的列表框中选择颜色以应用更改”“”
颜色=self.lbx.get(锚定)
msgselect=msg.askokcancel(
“车窗颜色”,“确认车窗的颜色”)
如果msgselect==True:
root.configure(bg=color)
自我毁灭
其他:
自我毁灭
root2=listbox()
根2.几何形状(“300x200”)
根2.标题(“窗口颜色”)
root2.listbx()
root2.mainloop()
如果名称=“\uuuuu main\uuuuuuuu”:
#基本启动
root=记事本()
根几何(“800x700”)
root.title(“Notepad-Untitled-1”)
根目录
root.textwid()
root.wm_iconbitmap(“noteicon.ico”)
root.mainloop()

谢谢大家!

所以马上就有几个危险信号。。。(多个
mainloop
调用,类中的类,在
listbox
内调用
root

似乎您缺少了许多gui框架的一个主要概念,即1个窗口不是1个应用程序。一般来说,“根”
from tkinter import *
from tkinter import messagebox as msg
from tkinter.filedialog import askopenfilename, asksaveasfilename
from functools import partial
import os

class Notepad(Tk):

    """Class for notepad """
#  Command for menus-

    def newFile(self):
 
        self.crfile = None
        self.txtarea.delete(1.0, END)

    def saveFile(self):

        if self.crfile == None:
            self.crfile = asksaveasfilename(initialfile="Untitled.txt",
                                            defaultextension=".txt", filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")])
            if self.crfile == "":
                self.crfile = None
            else:
                # Save as new file
                with open(self.crfile, "w") as f:
                    f.write(self.txtarea.get(1.0, END))
                    self.title(os.path.basename(
                        self.crfile + "- Tanish's Notepad"))
        else:
            # Save the file
            with open(self.crfile, "w") as f:
                f.write(self.txtarea.get(1.0, END))
                self.title(os.path.basename(
                    self.crfile + "- Tanish's Notepad"))

    def openFile(self):

        self.crfile = askopenfilename(defaultextension=".txt", filetypes=[
                                      ("All Files", "*.*"), ("Text Documents", "*.txt")])
        if self.crfile == "":
            self.crfile = None
        else:
            self.title(os.path.basename(self.crfile) +
                       "-" + "Tanish's Notepad")
            self.txtarea.delete(1.0, END)
            with open(self.crfile, "r") as f:
                self.txtarea.insert(1.0, f.read())

    # commands for edit menu-

    def copy(self):
        self.txtarea.event_generate(("<<Copy>>"))

    def paste(self):
        self.txtarea.event_generate(("<<Paste>>"))

    def cut(self):
        self.txtarea.event_generate(("<<Cut>>"))

    # commands for help menu-

    def About(self):
        msg.showinfo("Tanish's Notepad -Help",
                     "This is a simple notepad made by Tanish Sarmah")

    def menus(self):

        # TODO Menus
        mainmenu = Menu(self, tearoff="0")
        # file menu
        file = Menu(mainmenu, tearoff=0)
        # Creating new file
        file.add_command(label="New", command=self.newFile)
        # Saving the current file
        file.add_command(label="Save", command=self.saveFile)
        # Opening a Pre-Existing file
        file.add_command(label="Open", command=self.openFile)
        file.add_separator()
        file.add_command(label="Exit", command=self.destroy)  # Exit command
        mainmenu.add_cascade(menu=file, label="File")
        self.config(menu=mainmenu)

        # Edit menu---
        edit = Menu(mainmenu, tearoff=0)
        # To cut any part of the Textarea
        edit.add_command(label="Cut", command=self.cut)
        # To copy any part of the Textarea
        edit.add_command(label="Copy", command=self.copy)
        # To paste any cut or copied Text.
        edit.add_command(label="Paste", command=self.paste)
        mainmenu.add_cascade(menu=edit, label="Edit")
        self.config(menu=mainmenu)

        # Help menu---
        helpm = Menu(mainmenu, tearoff=0)
        # Displays about the notepad
        helpm.add_command(label="About", command=self.About)
        mainmenu.add_cascade(menu=helpm, label="Help")
        self.config(menu=mainmenu)

        # Window menu
        win = Menu(mainmenu, tearoff=0)
        win.add_command(label="Colour", command=partial(listbox, self)) #we'll use a partial functino to bind self as the parent here. listbx is now called in __init__
        mainmenu.add_cascade(menu=win, label="Window")
        self.config(menu=mainmenu)

    def textwid(self):

        # TODO Text widget---

        self.txtarea = Text(self)
        self.crfile = None
        self.txtarea.pack(expand=True, fill=BOTH)
        # TODO Scrollbar---
        self.scbar = Scrollbar(self.txtarea)
        self.txtarea.config(yscrollcommand=self.scbar.set)
        self.scbar.config(command=self.txtarea.yview)
        self.scbar.pack(side=RIGHT, fill=BOTH)

class listbox(Toplevel): 
    #listbox moved to its own class to prevent confusion of inheritance
    #child windows should not inherit from application root, rather from "Toplevel"
    def __init__(self, parent): 
        #moved window setup to __init__ method as we are creating a new window each time we want this menu
        #calling mainloop() is not necessary, as the "mainloop" from if __name__ == "__main__": is now running
        super().__init__()
        self.parent = parent #we need access to the parent so we chan change its color
        self.geometry("300x200")
        self.title("Window-Colour")
        self.listbx()
    
    def listbx(self):
        self.lbx = Listbox(self)
        colours = ["blue", "red", "yellow",
                    "grey", "green", "light blue", "black"]
        for c in colours:
            self.lbx.insert(END, c)
        self.lbx.pack()
        self.lbx.bind("<<ListboxSelect>>", self.selection)

    def selection(self, event):
        """Selection of colour from the  lisbox above to apply changes"""
        colour = self.lbx.get(ANCHOR)
        msgselect = msg.askokcancel(
            "Window-Colour", "Confirm the colour to apply to the window")
        if msgselect == True:
            self.parent.configure(bg=colour) #call the parent without a global because we inherited it earlier
            self.destroy()
        else:
            self.destroy()
        

if __name__ == "__main__":
    # Basic tkinter startup

    root = Notepad()
    root.geometry("800x700")
    root.title("Tanish's Notepad-Untitled-1")
    root.menus()
    root.textwid()
    # root.wm_iconbitmap("noteicon.ico") #I didn't have this file, so I commented it out
     
    root.mainloop()