为什么我的tkinter窗口对象(OOP tkinter)不能同时显示?

2024-09-29 19:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从面向对象的角度来学习tkinter,这样我就可以创建多个窗口

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

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

主.py:

import humanclass
from tkinter import *

window = Tk()

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

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

window.mainloop()

人形类.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()

如果有人能帮我指出我有限理解中的错误,我将不胜感激


Tags: textnamefrompyimportselftkinterdef
1条回答
网友
1楼 · 发布于 2024-09-29 19:29:58

这是因为窗口只有一个活动窗口,即根窗口。如果要创建多个窗口,则需要从根窗口派生它们。简单地给那个窗口分配一些东西,就会覆盖以前存在的任何东西。这就是为什么只显示最下面的实例。虽然从技术上讲,您可以实现线程和运行两个根窗口和两个主循环,但强烈建议不要这样做

您应该做的是在根窗口之外创建顶级实例。把它们看作是独立的弹出窗口。可以使它们独立于根窗口,也可以将它们锚定到根窗口。这样,如果您关闭根窗口,它的所有顶层都将关闭。我建议你多看看顶级,你会找到你想要的。你可能想要这样的东西:

主.py

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()

人形类.py

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()

相关问题 更多 >

    热门问题