'Python: tkinter - how to dynamically generate grids?

My application should look as follows:

  • If I click in BasicWindow at Button "Left" and click in NewWindow (should be some widget in seperate class) at Button "apply", in a cell of some grid (4 columns) below of Button "Left" the word hello should appear. If I repeat that n times, new words "Hello" should arranged in the grid below of the "Left" button n times.

  • If I click in BasicWindow at Button "Right" and click in NewWindow at Button "apply", in a cell of some grid (4 columns) below of Button "Left" the word hello should appear. If I repeat that n times, new words "Hello" should arranged in the grid below of the "Right" button n times.

This graphic illustrates, what the program should do: enter image description here

I just tried to solve that with following code:

from tkinter import *

class NewWindow(Toplevel):
    def __init__(self, master = None, apply=None):
        super().__init__(master = master)
        self.title('NewWindow')
        self.master = master
        self.words = 'Hello'

 
        self.bt1 = Button(self, text="apply", command=self.bt_press)
        self.bt1.grid(column=0, row=0)
        self.apply = apply
    def bt_press(self):
        self.apply(self.words)
        self.destroy()

window = Tk()

def new_Editor(key):
    def make_label1(lbl_txt):
        lbl = Label(window, text=lbl_txt)
        lbl.grid(column=0,row=2)
    def make_label2(lbl_txt):
        lbl = Label(window, text=lbl_txt)
        lbl.grid(column=2,row=2)

    if key == 1:
        a = NewWindow(window, make_label1)
    else:
        a = NewWindow(window, make_label1)

window.title("BasicWindow")

window.basic_bt_l = Button(window, text="Left", command=lambda: new_Editor(1))
window.basic_bt_l.grid(column=0, row=0, columnspan=2)


window.basic_bt_r = Button(window, text="Right", command=lambda: new_Editor(2))
window.basic_bt_r.grid(column=1, row=0)

window.mainloop()

My Programm looks like this:

enter image description here

For some reason the two buttons are not very good arranged and the format of the output isn't very good. How can I just define some well formatet grid between Left and Right button and two grids below of Left/Right button with the properties I descriped above?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source