Python Tkinter小部件添加到根窗口而不是Toplevel窗口

时间:2018-02-12 22:06:50

标签: python python-2.7 tkinter

在这里使用Python 2.7。我正在尝试添加一个基本设置窗口,但是当我打开Toplevel窗口并尝试向其添加小部件时,小部件会被添加到主窗口中。这是一个例子:

import Tkinter as tk

class MainWindow (tk.Frame):
    def __init__ (self, root):
        tk.Frame.__init__(self, root)
        self.root = root
        self.root.geometry("300x200")
        button = tk.Button(self, text="Settings", command=self.open_settings).pack()

    def open_settings (self):
        settings_win = tk.Toplevel(self.root, height=300, width=400)
        settings_win.focus_set()

        top_frame = tk.Frame(settings_win, bg="red").pack(side="top", fill="both", expand=True)
        bottom_frame = tk.Frame(settings_win, bg="blue").pack(side="bottom", fill="both", expand=True)

        top_label = tk.Label(top_frame, text="Top Label").pack()
        bottom_label = tk.Label(bottom_frame, text="Bottom Label").pack()

if __name__ == '__main__':
    root = tk.Tk()
    MainWindow(root).pack(fill="both", expand=True)
    root.mainloop()

以下是点击下方的设置按钮时看到的内容。第二个窗口打开,但标签显示在主窗口上。

enter image description here

1 个答案:

答案 0 :(得分:1)

因为你的包装在同一行,请查看这个问题的答案,他详细解释了这一点:Python - Tkinter - Widgets created inside a class inherited from Toplevel() appear in a different frame OUTSIDE the class, Toplevel() class is empty

这应该解决它:

    top_frame = tk.Frame(settings_win, bg="red")
    top_frame.pack(side="top", fill="both", expand=True)
    bottom_frame = tk.Frame(settings_win, bg="blue")
    bottom_frame.pack(side="bottom", fill="both", expand=True)

    top_label = tk.Label(top_frame, text="Top Label")
    top_label.pack()
    bottom_label = tk.Label(bottom_frame, text="Bottom Label")
    bottom_label.pack()

这是一个截图: enter image description here