在 TopLevel 窗口中使用 grid() 未按预期布置小部件

问题描述 投票:0回答:2

我正在尝试使用 grid() 布局管理器来应用于成功打开的 Toplevel 窗口,但我只能让 pack() 工作。似乎使用 grid(row=x, column=y) 不起作用 - 请问我错过了什么? 我正在使用以下代码:

def messageWindow():
# create child window
win = Toplevel()
win.geometry("400x400")

# display message
message = "This is the child window"
my_label = Label(win, text=message)
my_label.grid(row=5, column=8)
# quit child window and return to root window
# the button is optional here, simply use the corner x of the child window
#close_btn = Button(win, text='Close', command=win.destroy).place(x=150, y=200) -- this works but I want to use grid()
close_btn = Button(win, text='Close', command=win.destroy).grid(row=1, column=1)

当使用菜单命令触发时,返回以下结果: enter image description here

我希望 grid() 布局管理器能够区分我为标签和按钮小部件指定的行/列参数。

相同的 grid() 布局管理器在引用父窗口=Tk() 时起作用。

python tkinter grid toplevel
2个回答
0
投票

这里是适用于

grid()
place()
的功能代码。在对 OP 代码进行一些重组,并结合 martineau 和 Сергей Кох 的评论后,它创建了带有标题的根窗口和子窗口。

假设从 OP 来看,子窗口只有 6 行 9 列,并且 Label 位于右下角,“关闭”按钮位于左上角,然后使用

rowconfigure()
columnconfigure()
grid()
sticky
参数一起正确定位这些小部件。

import tkinter as tk

def messageWindow():
    child_win = tk.Toplevel()
    child_win.geometry("400x400")
    child_win.title('Child')

    child_win.rowconfigure(1, weight=1)
    child_win.columnconfigure(1, weight=1)

    # display message
    message = "This is the child window"
    my_label = tk.Label(child_win, text=message)
    my_label.grid(row=5, column=8)

    # quit child window and return to root window
    # the button is optional here, simply use the corner x of the child window

    close_btn = tk.Button(child_win,
                          text='Close',
                          command=child_win.destroy)

    # Either of these two statements work: .grid() puts close_btn
    #  in the top left corner, while .place() puts it near the
    #  center with the given coordinates and window geometry.
    close_btn.grid(row=1, column=1, sticky=tk.NW)
    # close_btn.place(x=150, y=200)

if __name__ == '__main__':
    root = tk.Tk()
    root.title('This is the root window')
    root.geometry("400x200")
    messageWindow()
    root.mainloop()

-1
投票

这就是你想要的,就像你截图一样吗?

截图:

我只是改变了

row
column

  • my_label.grid(行=0,列=1)
  • close_btn = Button(win, text='Close', 命令=win.destroy).grid(行=1,列=0)
© www.soinside.com 2019 - 2024. All rights reserved.