Search code examples
pythontkintergrid

How do I make a function that increases the column by 1 every time a button is pressed in tkinter?


I'm working on a project in python, and I want to make a button that shifts the AddButton to the next column and puts a Network in its place.

My code below:

class NetAppHomePG:
    def __init__(self):
        self.x = 0
        self.y = 1

        self.AddImg = ImageTk.PhotoImage(Image.open("c:/Users/Will/Desktop/VSC_Test/NetworkApp/plus.png"))
        self.AddButton = Button(self.TabsFrame, image=self.AddImg, command=self.Add_Network).grid(row=0, ,column=1, padx=250, pady=0)

        self.NavBarFrame.grid(sticky=W)
        self.TabsFrame.grid(sticky=W)
       
        self.win.mainloop()

    def Add_Network(self):
        self.x =+ 1
        self.y =+ 1
        self.Network = Canvas(self.TabsFrame, width=400, height=600, background="grey")
        self.Network = Label(self.TabsFrame, text="Network #1", font=("Roboto", 18), foreground="lightblue", background="grey")
        self.Network.grid(row=0, column=(self.x), padx=250, pady=0)
        self.AddButton.grid(row=0, column=(self.y), padx=250, pady=0)

I tried assigning the AddButtons column to another variable and then incrementing the variable by one every time the button is pressed.


Solution

  • Try setting up the grid inside tabsFrame with rowconfigure and columnconfigure, and clear the button with grid_forget before replacing it with another call to grid

    class NetAppHomePG:
        def __init__(self):
        ...  # code omitted for brevity
        self.TabsFrame.rowconfigure(1, weight=1)
        self.TabsFrame.columnconfigure(1, weight=1)
        
        def Add_Network(self):
            self.x =+ 1
            self.y =+ 1
            self.Network = Canvas(self.TabsFrame, width=400, height=600, background="grey")
            self.Network = Label(self.TabsFrame, text="Network #1", font=("Roboto", 18), foreground="lightblue", background="grey")
            self.Network.grid(row=0, column=(self.x), padx=250, pady=0)
            
            self.AddButton.grid_forget()  # clear the button before replacing it below
            self.AddButton.grid(row=0, column=(self.y), padx=250, pady=0)