gpt4 book ai didi

python - 在 Python (Tkinter) 的同一窗口内混合两个布局管理器

转载 作者:行者123 更新时间:2023-11-28 22:21:29 26 4
gpt4 key购买 nike

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

我有这个棋盘:

enter image description here

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

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

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

enter image description here

我怎样才能实现它?

提前致谢

最佳答案

你不使用 grid要创建检查板,您可以使用 grid仅将 Canvas 放在窗口中。

Canvasrow=0所以你可以把它放在row=2然后你可以把Labelsrow=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()

enter image description here

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

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

如果你真的需要混合管理器,那么你也可以输入 Framerow=0Canvasrow=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)

关于python - 在 Python (Tkinter) 的同一窗口内混合两个布局管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48328498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com