我正在为TKinter的游戏创建一个网格,我希望在蓝色网格的网格下面或旁边有按钮。我已经尝试过了:
from tkinter import *
class BattleScreen(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.grid()
for row in range(20):
for col in range(20):
butt1 = Button(self, bg='blue', width=1)
butt1.grid(row=row, column=col)
#self.but_frame = Frame(self)
#self.but_frame.pack(fill=X)
button1 = Button(self, text='Quit', width=6, command=lambda root=root:root.destroy())
button1.grid(row=21)
root = Tk()
sheet = BattleScreen(root)
root.mainloop()
当它运行时,它会在蓝色瓷砖下方创建按钮,但由于它全部位于同一网格上并且按钮较宽,因此它会弄乱按钮上方的所有内容。
你看到的两行代码注释了我试图创建另一个与网格框架分开的框架以打开按钮,但我想你不能这样做。我错了吗?
如何在不弄乱蓝色瓷砖对齐的情况下,在网格中的蓝色瓷砖下方或旁边显示按钮?
答案 0 :(得分:3)
对我来说,最简单的方法是使用两个框架 - 一个用于按钮网格,另一个用于其他按钮。然后,您可以将这些并排打包到顶部到底部。然后,使用网格作为按钮网格,使用网格或打包其他按钮。
这样,网格和按钮在逻辑上是不同的,您可以将它们各自放置,而不用担心它们如何影响显示器的其余部分。这使您的程序 更容易维护并随着时间的推移而增长。
请注意,在下文中,我从self.grid()
中删除了BattleScreen
- 我认为框架将其自身置于其父级中是不好的做法。父母应控制安置。
from tkinter import *
class BattleScreen(Frame):
def __init__(self, root):
Frame.__init__(self, root)
for row in range(20):
for col in range(20):
butt1 = Button(self, bg='blue', width=1)
butt1.grid(row=row, column=col)
class Controls(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.quit = Button(self, text="Quit", width=6,
command=root.destroy)
self.quit.pack()
root = Tk()
screen = BattleScreen(root)
controls = Controls(root)
controls.pack(side="bottom", fill="x")
screen.pack(side="top", fill="both", expand=True)
root.mainloop()
答案 1 :(得分:0)