【问题标题】:Tkinter widget opens two windowsTkinter 小部件打开两个窗口
【发布时间】:2015-06-30 01:34:26
【问题描述】:

我在 Win 机器上运行 Tkinter 3.5,当我运行这段代码时,我得到了两个 windows 。我只期待一个。顺便说一句,我从网上得到了代码。它工作正常,除了第二个(在背景中)窗口让我感到困扰。 基本上是一个用按钮浏览不同窗口(页面)的小部件。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

try:
    import Tkinter as tk  # Python2
except ImportError:
    import tkinter as tk  # Python3

class Wizard(tk.Toplevel):
    def __init__(self, npages, master=None):

        self.pages = []
        self.current = 0
        tk.Toplevel.__init__(self)

        self.attributes('-topmost', True)


        for page in range(npages):
            self.pages.append(tk.Frame(self))
        self.pages[0].pack(fill='both', expand=1)
        self.__wizard_buttons()

    def onQuit(self):
        pass 

    def __wizard_buttons(self):
        for indx, frm in enumerate(self.pages):
            btnframe = tk.Frame(frm, bd=1, bg='#3C3B37')
            btnframe.pack(side='bottom', fill='x')
            nextbtn = tk.Button(btnframe, bd=0, bg='#F2F1F0', activebackground='#F58151', highlightcolor='red', cursor='hand2', text="Siguiente >>", width=10, command=self.__next_page)
            nextbtn.pack(side='right', anchor='e', padx=5, pady=5)
            if indx != 0:
                prevbtn = tk.Button(btnframe, bd=0, bg='#F2F1F0', activebackground='#F58151', highlightcolor='red', cursor='hand2', text="<< Atras", width=10, command=self.__prev_page)
                prevbtn.pack(side='right', anchor='e', padx=5, pady=5)
                if indx == len(self.pages) - 1:
                    nextbtn.configure(text="Terminar", bd=0, bg='#F2F1F0', activebackground='#F58151', highlightcolor='red', cursor='hand2', command=self.close)

    def __next_page(self):
        if self.current == len(self.pages):
            return
        self.pages[self.current].pack_forget()
        self.current += 1
        self.pages[self.current].pack(fill='both', expand=1)

    def __prev_page(self):
        if self.current == 0:
            return
        self.pages[self.current].pack_forget()
        self.current -= 1
        self.pages[self.current].pack(fill='both', expand=1)

    def add_page_body(self, body):
        body.pack(side='top', fill='both', padx=6, pady=12)

    def page(self, page_num):
        try:
            page = self.pages[page_num]
        except KeyError("Pagina Invalida! : %s" % page_num):
            return 0
        return page

    def close(self):
        if self.validate():
            self.master.iconify()
            print (' TK Wizard finished... ')
            self.destroy()
            self.master.destroy()

    def validate(self):
        return 1 

if __name__ == "__main__":
    root = tk.Tk()
    root.title(' TK Wizards ')
    wizard = Wizard(npages=3, master=root)
    wizard.minsize(400, 350)
    page0 = tk.Label(wizard.page(0), text='Pagina 1: ...Bienvenido al Wizard de TK !')
    page1 = tk.Label(wizard.page(1), text='Pagina 2: Acepta las condiciones de la WTFPL ?')
    page2 = tk.Label(wizard.page(2), text='Pagina 3: Felicitaciones, nada no se ha instalado correctamente.')
    wizard.add_page_body(page0)
    wizard.add_page_body(page1)
    wizard.add_page_body(page2)
    root.mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    附加的空白窗口是根窗口。添加调用

    root.withdraw()
    

    就在root.title(' TK Wizards ') 行的下方,应该可以解决问题

    【讨论】:

    • 乐于助人。如果解决了您的问题,请考虑accepting 的答案,让其他用户知道问题已解决。
    【解决方案2】:

    main 区域,你创建一个tkinter 对象,它会产生一个窗口:

    root = tk.Tk()
    

    然后,在Wizard 类的__init__ 中,创建一个Toplevel 对象:

    tk.Toplevel.__init__(self)
    

    所以您实际上是在这个新的Toplevel 窗口中创建 GUI。您可以更改程序以在根窗口中创建应用程序,这需要更改 Wizard 类以继承默认的 object 并更改程序以对保存的 self.master 根对象执行操作Wizard 对象(不再是 Toplevel 对象)。

    try:
        import Tkinter as tk  # Python2
    except ImportError:
        import tkinter as tk  # Python3
    
    class Wizard(object):
        def __init__(self, npages, master=None):
    
            self.pages = []
            self.current = 0
            self.master = master
            self.master.attributes('-topmost', True)
    
    
            for page in range(npages):
                self.pages.append(tk.Frame(self.master))
            self.pages[0].pack(fill='both', expand=1)
            self.__wizard_buttons()
    
        def onQuit(self):
            pass 
    
        def __wizard_buttons(self):
            for indx, frm in enumerate(self.pages):
                btnframe = tk.Frame(frm, bd=1, bg='#3C3B37')
                btnframe.pack(side='bottom', fill='x')
                nextbtn = tk.Button(btnframe, bd=0, bg='#F2F1F0', activebackground='#F58151', highlightcolor='red', cursor='hand2', text="Siguiente >>", width=10, command=self.__next_page)
                nextbtn.pack(side='right', anchor='e', padx=5, pady=5)
                if indx != 0:
                    prevbtn = tk.Button(btnframe, bd=0, bg='#F2F1F0', activebackground='#F58151', highlightcolor='red', cursor='hand2', text="<< Atras", width=10, command=self.__prev_page)
                    prevbtn.pack(side='right', anchor='e', padx=5, pady=5)
                    if indx == len(self.pages) - 1:
                        nextbtn.configure(text="Terminar", bd=0, bg='#F2F1F0', activebackground='#F58151', highlightcolor='red', cursor='hand2', command=self.close)
    
        def __next_page(self):
            if self.current == len(self.pages):
                return
            self.pages[self.current].pack_forget()
            self.current += 1
            self.pages[self.current].pack(fill='both', expand=1)
    
        def __prev_page(self):
            if self.current == 0:
                return
            self.pages[self.current].pack_forget()
            self.current -= 1
            self.pages[self.current].pack(fill='both', expand=1)
    
        def add_page_body(self, body):
            body.pack(side='top', fill='both', padx=6, pady=12)
    
        def page(self, page_num):
            try:
                page = self.pages[page_num]
            except KeyError("Pagina Invalida! : %s" % page_num):
                return 0
            return page
    
        def close(self):
            if self.validate():
                self.master.iconify()
                print (' TK Wizard finished... ')
                self.destroy()
                self.master.destroy()
    
        def validate(self):
            return 1 
    
    if __name__ == "__main__":
        root = tk.Tk()
        root.title(' TK Wizards ')
        wizard = Wizard(npages=3, master=root)
        wizard.master.minsize(400, 350)
        page0 = tk.Label(wizard.page(0), text='Pagina 1: ...Bienvenido al Wizard de TK !')
        page1 = tk.Label(wizard.page(1), text='Pagina 2: Acepta las condiciones de la WTFPL ?')
        page2 = tk.Label(wizard.page(2), text='Pagina 3: Felicitaciones, nada no se ha instalado correctamente.')
        wizard.add_page_body(page0)
        wizard.add_page_body(page1)
        wizard.add_page_body(page2)
        root.mainloop()
    

    【讨论】:

    • 得到错误文件 "C:\Program Files\Python 3.5\lib\tkinter_init_.py",第 2095 行,在 _setup self.tk = master.tk AttributeError: '向导'对象没有属性'tk'
    • 抱歉,我无法重现该错误。发布的代码在我的机器(Windows 7,Python 3.4.2)上运行良好。实际程序中的哪一行导致了错误?
    • TigerhawkT3,对不起。没有进行所有建议的更改。您的代码完美运行。谢谢!!!!
    • @Martin,如果这解决了问题,您可以通过单击投票按钮下方的复选标记接受它。
    猜你喜欢
    • 2018-11-17
    • 2013-09-18
    • 2017-01-17
    • 1970-01-01
    • 2018-05-11
    • 2019-08-07
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多