Search code examples
pythontkintertkinter-entry

Creating a grid of buttons


I can not figure out how to make a grid of the received buttons I tried to do it with grid but it gives an error

_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack

I can't figure out how to implement it. As I understand it, he swears at the fact that he already uses pack on the buttons. How else?

import random as rn
import tkinter as tk
def main_fun():
    m = []
    min = int(ent1.get())
    max = int(ent2.get())
    cel = int(ent3.get())
    while cel > 0:
        count = rn.randint(min,max)
        cel -= count
        if cel >= 0:
            m.append(count)
        else:
            m.append(count - (cel + count))
    button_count = len(m)
    for i in range(button_count):
        button = tk.Button(win, text=str(m[i]))
        button.grid(row=i+1, columnspan=2, padx=5, pady=5)
win = tk.Tk()
btn1 = tk.Button(win, text="Create", command= main_fun)
btn1.pack()
ent1 = tk.Entry(win)
ent1.pack()
ent2 = tk.Entry(win)
ent2.pack()
ent3 = tk.Entry(win)
ent3.pack()
win.mainloop()

Solution

  • Put your button in a frame instead of on the root window:

    for i in range(button_count):
            frame = tk.Frame(win)
            button = tk.Button(frame, text=str(m[i]))
            button.grid(row=i+1, columnspan=2, padx=5, pady=5)
            frame.pack()
    

    You cannot use multiple geometry managers (.pack(), .place(), or .grid()) in the same frame/window, which means that in order to use grid() on a widget alongside pack(), it needs to be in a separate frame from the widgets you are displaying with pack(). Then, once you've used grid() on the widgets you want in the separate frame, you can then use frame.pack() to place the frame inside the root window with the rest of your widgets.

    Alternatively, if you don't need to use grid(), just use pack() on the button :)

    for i in range(button_count):
            button = tk.Button(win, text=str(m[i]))
            button.pack()