我对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()
问题是我想在棋盘上添加前一行,它不属于网格布局。像这样:
我怎样才能实现它?
提前致谢
答案 0 :(得分:2)
您没有使用grid
来创建核对,您只能使用grid
将画布放在窗口中。
Canvas
位于row=0
,因此您可以将其放入row=2
,然后您可以将Labels
放入row=0
和row=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()
您可以使用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()
如果您真的需要混合经理,那么您也可以将Frame
放在row=0
和Canvas
row=1
中,然后在pack()
内使用Frame
{ {1}}
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)
答案 1 :(得分:0)
最佳解决方案是为棋盘创建一个框架,然后您可以在该框架中创建小部件。在主窗口中,您可以使用任何要添加棋盘格和任何其他窗口小部件的几何管理器。
尽管如此,在这种特定情况下,您只需将画布移动到第一行,然后在第0行添加任何其他内容。