簡體   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