1

I am sure this is a duplicate question, but I cannot seem to find the solution. Perhaps it is my search terms. Either way, I created a mock program for what I am actually trying to do, for simplicity. It seems when I initialize a button in tkinter it executes the command associated with the button. This is true for any button initialized after the initial button widgets created. Hopefully this makes sense. Here is the complete code to demonstrate what I am talking about.

from tkinter import *

class Application(Frame):
def __init__(self, master):
    super(Application, self).__init__(master)
    self.grid()
    self.create_start_button()

def create_start_button(self):
    self.bttnStart = Button(self)
    self.bttnStart["text"] = "Load new buttons"
    self.bttnStart["command"] = self.create_secondary_buttons

    self.bttnStart.grid(row=0,column=0,sticky=W)

def create_secondary_buttons(self):
    label_text = "This is a label"

    self.bttnTwo = Button(self)
    self.bttnTwo["text"] = "Load label"
    self.bttnTwo["command"] = self.create_label(label_text)

    self.bttnTwo.grid(row=1,column=0,sticky=W)

def create_label(self, label_text):
    self.lblLabel = Label(self)
    self.lblLabel["text"] = label_text

    self.lblLabel.grid(row=2,column=0,sticky=W)

root = Tk()
root.title("Button program")
root.geometry("500x600")
app = Application(root)
root.mainloop()

When I click "Load new buttons" button it will execute the create_secondary_buttons command, but also execute the self.bttnTwo command, self.create_label.

I am new to tkinter and still learning the ropes. I have tried initializing all the buttons in the create_start_button method, but it not helpful. Thanks in advance!

thebtcfuture
  • 37
  • 2
  • 4
  • I realized it has to do with the parameters I am passing through command. Is it possible to pass parameters to functions through tkinter buttons? – thebtcfuture Jan 04 '19 at 05:09
  • @bryan-oakley if you are going to close it at least link an answer that's actually useful. Lambda obviously won't work for OP. – Novel Jan 04 '19 at 05:10
  • @Novel: why do you think won't lamba work? – Bryan Oakley Jan 04 '19 at 05:13
  • @bryan-oakley Because I didn't see that the variable was defined inside the same function; I thought it was being passed it. My apologies, I should have read better, as you were. – Novel Jan 04 '19 at 05:15
  • @thebtcfuture: yes. The linked-to question mentioned two ways to do it, and gives an example using `lambda`. – Bryan Oakley Jan 04 '19 at 05:17

0 Answers0