How can I make an infinity cycle creating buttons (tkinter)?

50 views Asked by At

I want to create button and if pressed it - creates a new but and so on (infinity cycle basically). But it works just one time - create only one additional button.


from tkinter import *

class Application(Frame):
    rw = 0
    cl = 0
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.btn1 = Button(self, text = 'Create  a new button')
        self.btn1.grid(row = 0, column = 0, sticky = W)
        self.btn1['command'] = self.new_button

    def new_button(self):
        rw = 1
        cl = 1
        self.btn1 = Button(self, text = 'Create  a new button')
        self.btn1.grid(row = rw, column = cl, sticky = W)
        rw+=1
        cl+=1

root = Tk()
root.title('King of the Kings!')
root.geometry('400x205')
app = Application(root)
root.mainloop()

Cheers!

1

There are 1 answers

0
Devansh Soni On BEST ANSWER

Here are a few changes in your code. I've made rw and cl instance variables and also removed the lines rw = 1 and cl = 1 because every time the function is called, it creates a new button but places it directly above the first button at position (1, 1).

from tkinter import *

class Application(Frame):
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.rw = 1      # Made rw and cl instance variables
        self.cl = 1      #
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.btn1 = Button(self, text = 'Create a new button')
        self.btn1.grid(row = 0, column = 0, sticky = W)
        self.btn1['command'] = self.new_button

    def new_button(self):
        self.btn1 = Button(self, text = 'Create a new button')
        self.btn1.grid(row=self.rw, column=self.cl, sticky = W)
        self.rw += 1
        self.cl += 1

root = Tk()
root.title('King of the Kings!')
root.geometry('400x205')
app = Application(root)
root.mainloop()