在 Python 中的同一个 window 中混合两个布局管理器 (Tkinter)

Mixing two layout managers inside the same window in Python (Tkinter)

我是Python和Tkinter的新手,所以我希望这个问题对前辈们来说很简单...

我有这个棋盘:

我正在使用网格布局管理,如下所示:

from tkinter import *

def checkerboard(can):
    w = can.winfo_width()
    h = can.winfo_height()
    cellwidth = w / 4
    cellheight = h / 4

    for row in range(4):
        for col in range(4):
            x1=col * cellwidth
            y1=row * cellheight
            x2=(col + 1) * cellwidth
            y2=(row + 1) * cellheight
            can.create_rectangle(col * cellwidth, row * cellheight, (col + 1) * cellwidth, (row + 1) * cellheight,
                                 fill='white')
            can.create_text(((x1+x2)/2,(y1+y2)/2),text='A')

window = Tk()
thecanvas = Canvas(window, width=500, height=500)
thecanvas.grid(row=0, column=0)
window.update_idletasks()
checkerboard(thecanvas)
window.mainloop()

问题是我想在棋盘上方添加一条不属于网格布局的前一行。像这样:

如何实现?

提前致谢

最好的解决方案是为棋盘创建一个框架,然后您可以在该框架中创建小部件。在主要 window 中,您可以使用任何要添加棋盘和任何其他小部件的几何管理器。

不过,在这种特定情况下,您只需将 canvas 移动到第一行并在第 0 行中添加任何其他内容即可。

您不使用grid创建棋盘,您使用grid只是将canvas放入window。

Canvasrow=0所以你可以把它放在row=2然后你可以把Labels放在row=0row=1

l1 = Label(window, text="I WANT TO CREATE THIS LABEL")
l1.grid(row=0, column=0)

l2 = Label(window, text="AND THIS TOO", fg='red')
l2.grid(row=1, column=0)

thecanvas = Canvas(window, width=500, height=500)
thecanvas.grid(row=2, column=0)

完整代码

from tkinter import *

def checkerboard(can):
    w = can.winfo_width()
    h = can.winfo_height()
    cellwidth = w / 4
    cellheight = h / 4

    for row in range(4):
        for col in range(4):
            x1=col * cellwidth
            y1=row * cellheight
            x2=(col + 1) * cellwidth
            y2=(row + 1) * cellheight
            can.create_rectangle(col * cellwidth, row * cellheight, (col + 1) * cellwidth, (row + 1) * cellheight,
                                     fill='white')
            can.create_text(((x1+x2)/2,(y1+y2)/2),text='A')

window = Tk()

l1 = Label(window, text="I WANT TO CREATE THIS LABEL")
l1.grid(row=0, column=0)

l2 = Label(window, text="AND THIS TOO", fg='red')
l2.grid(row=1, column=0)

thecanvas = Canvas(window, width=500, height=500)
thecanvas.grid(row=2, column=0)

window.update_idletasks()
checkerboard(thecanvas)
window.mainloop()

你甚至可以使用 pack() 而不是 grid(),你会得到相同的结果

l1 = Label(window, text="I WANT TO CREATE THIS LABEL")
l1.pack()

l2 = Label(window, text="AND THIS TOO", fg='red')
l2.pack()

thecanvas = Canvas(window, width=500, height=500)
thecanvas.pack()

如果你真的需要混合经理那么你也可以把Frame放在row=0Canvas放在row=1然后你可以使用pack()里面 Frame

frame = Frame(window)
frame.grid(row=0, column=0)

l1 = Label(frame, text="I WANT TO CREATE THIS LABEL")
l1.pack()

l2 = Label(frame, text="AND THIS TOO", fg='red')
l2.pack()

thecanvas = Canvas(window, width=500, height=500)
thecanvas.grid(row=1, column=0)