0
votes
from tkinter import *
from random import *

class Game:
    def __init__(self):
        self.root = Tk()

        self.frame1 = Frame(self.root, width = 1055, height = 30)
        self.frame1.pack()

        self.frame_lvl = Frame(self.root, width = 1055, height = 1055)
        self.frame_lvl.pack()

        for frame_lvl in range(0,31):
            self.frame_lvl = Frame(self.root)
            self.frame_lvl.pack(side = BOTTOM)
        for i in range(0,31):
            for j in range(0,31):
                button = Button(self.i, width = 30, height = 30, padx = 2, pady = 2)
                button.pack(side = LEFT)

        self.root.mainloop()

app = Game()

So I try to create a new frame level so the buttons won't keep printing on the same line but I'm not sure if the frame level will be saved as self.0, self.1, self.2, etc...

When I tried making the frame a grid and adjusting the width, height, rowspan, and column span, I got the error ("cannot use geometry manager grid inside . which already has slaves managed by pack") The error comes from these lines:

self.frame2 = Frame(width = 1055, height = 1055)
self.frame2.grid(columnspan = 30, rowspan = 30)

Any suggestions.

1

1 Answers

0
votes

Note that there is only one self.frame_lvl so each time you assign it a new value you lose the existing value. In the end it will only contain the last value assigned to it. Also

for i in range(31):
    for j in range(31):

creates 31*31 buttons(which is over 900 buttons). While you are learning, stick with all grid() or all pack() in a program until you learn how to mix the two. To create 3 rows of 5 buttons using grid()

from tkinter import *
from functools import partial

class Game:
    def __init__(self):
        self.root = Tk()

        self.frame1 = Frame(self.root, width = 900, height = 30)
        self.frame1.grid()

        self.label=Label(self.frame1, text="")
        self.label.grid(row=0, column=0, columnspan=5)

        ## save each button id in a list
        self.list_of_button_ids=[]
        for ctr in range(15):
            ## use partial to pass the button number to the
            ## function each time the button is pressed
            button = Button(self.frame1, text=str(ctr), width = 20,
                            height = 20, padx = 2, pady = 2,
                            command=partial(self.button_callback, ctr))
            this_row, this_col=divmod(ctr, 5)
            ## the label is in the top row so add one to each row
            button.grid(row=this_row+1, column=this_col)

            ## add button's id to list
            self.list_of_button_ids.append(button)
        self.root.mainloop()

    def button_callback(self, button_num):
        """ display button number pressed in the label
        """
        self.label.config(text="Button number %s and it's id=%s"
                   % (button_num, self.list_of_button_ids[button_num]))


app = Game()