Reputation: 147
I'm working on a minesweeper game in Python and am running into problems when creating the graphics using Tkinter.
The minesweeper array is made up of buttons created through a different class. I place these in the window using grid(). However when I want to place additional items in the window, such as checkbuttons and labels, they don't seem to work with the array of buttons. I'm trying to have the buttons in the top left of the window and a label just to the right of them. But when I try to place it there in the grid, it too ends up in the top left of the window no matter what row or column i specify.
I did not have this problem when I created the buttons in the same class as I placed them in, but for other reasons it's better for me to have them in different classes.
Here's a simplified version of what I'm trying to do:
from tkinter import *
class Square(Frame):
def __init__(self):
self.button=Button(text=" ")
class App(Frame):
def __init__(self,master):
super(App,self).__init__(master)
self.grid()
self.matrix=[[None for i in range(10)] for i in range(10)]
for x in range(10):
for y in range(10):
self.matrix[x][y]=Square()
self.matrix[x][y].button.grid(row=x,column=y)
self.label=Label(self, text="Hello")
self.label.grid(row=0, column=10)
root=Tk()
App(root)
root.mainloop()
Upvotes: 0
Views: 2308
Reputation: 386352
The root of the problem is that the widgets in the matrix have the root window as the parent, and the label has the inner frame as the parent. You should pass self
to the constructor of the Square
class (eg: self.matrix[x][y] = Square(self)) so that the buttons are children of the
App` class.
Personally, I think a better design is to have the matrix of buttons inside it's own frame, separate from other controls. I would create a Grid
class that is a frame and the buttons, and nothing else. Then, your main program becomes something like this:
class App(Frame):
def __init__(self, master):
self.matrix = Grid(self, 10, 10)
self.label = Label(self, text="Hello")
self.matrix.grid(row=0, column=0, sticky="nsew")
self.label.grid(row=0, column=1, sticky="nsew")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
Upvotes: 0