繁体   English   中英

为什么我的tkinter窗口对象(OOP tkinter)都没有显示?

[英]Why are my tkinter window objects (OOP tkinter) not BOTH showing?

我试图从OOP的角度学习tkinter,以便创建多个窗口。

我创建了两个文件(main.py和Humanclass.py)。

为什么两个窗口都没有创建? 我以为我已经创建了一个类,并且在主程序中使用不同的数据创建了该类的2个实例?

Main.py:

import humanclass
from tkinter import *

window = Tk()

human1 = humanclass.Human(window, "Jim", "78", "British")

human2 = humanclass.Human(window, "Bob", "18", "Welsh")

window.mainloop()

humanclass.py:

from tkinter import *


class Human():
    def __init__(self, window, name, age, nation):
        self.window=window
        self.window.geometry("500x200+100+200")
        self.window.title(name)
        self.label1 = Label(self.window, text=age).grid(row=0, column=0, sticky=W)
        self.label2 = Label(self.window, text=nation).grid(row=1, column=0, sticky=W)

        self.button = Button(self.window, text="Close", width=5, command=self.clicked).grid(row=3, column=0, sticky=W)

    def clicked(self):
        self.window.destroy()

我们将不胜感激为您提供帮助,帮助我了解我在有限的理解上的错误。

这是因为窗口只是一个活动窗口,即根窗口。 如果要创建多个窗口,则需要从该根窗口中生成它们。 简单地将内容分配给该窗口将覆盖以前的内容。 这就是为什么只显示底层实例的原因。 从技术上讲,您可以实施线程并使用两个主循环运行两个根窗口,但是强烈建议不要这样做。

您应该做的是在根窗口之外创建Toplevel实例。 可以将它们视为独立的弹出窗口。 您可以使它们独立于根窗口,也可以将其锚定到该窗口。 这样,如果您关闭根窗口,则所有关闭的顶级都将关闭。 我建议您进一步研究“顶级”,然后找到所需的内容。 您可能想要这样的东西:

主程序

import humanclass
from Tkinter import *

window = Tk()
# Hides the root window since you will no longer see it
window.withdraw()

human1 = humanclass.Human(window, "Jim", "78", "British")
human2 = humanclass.Human(window, "Bob", "18", "Welsh")


window.mainloop()

人类

from Tkinter import *


class Human():
    def __init__(self, window, name, age, nation):
        # Creates a toplevel instance instead of using the root window
        self.window=Toplevel(window)
        self.window.geometry("500x200+100+200")
        self.window.title(name)
        self.label1 = Label(self.window, text=age).grid(row=0, column=0, sticky=W)
        self.label2 = Label(self.window, text=nation).grid(row=1, column=0, sticky=W)

        self.button = Button(self.window, text="Close", width=5, command=self.clicked).grid(row=3, column=0, sticky=W)

    def clicked(self):
        self.window.destroy()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM