Hi!

The following Tkinter buttons should call opt_def with opt as 1 or 2 depending on which button is pressed (see code).

from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.opt1 = Button(frame, text="Opt1", command=self.opt_def(1))
        self.opt1.pack(side=TOP)

        self.opt2 = Button(frame, text="Opt2", command=self.opt_def(2))
        self.opt2.pack(side=BOTTOM)

    def opt_def(self, opt):
        print 'You have choosen option', opt
        

root = Tk()

app = App(root)

root.mainloop()

But when the code is ran (no Tkinter buttons pressed) it returns this:

>>> 
You have choosen option number 1
You have choosen option number 2

Why does this happens and how do I fix it? Sorry about my spelling btw, I'm not american

The easiest way to do this is with a pass-through function.

from Tkinter import *
 
class App:
 
    def __init__(self, master):
 
        frame = Frame(master)
        frame.pack()
 
        self.opt1 = Button(frame, text="Opt1", command=self.opt_1)
        self.opt1.pack(side=TOP)
 
        self.opt2 = Button(frame, text="Opt2", command=self.opt_2)
        self.opt2.pack(side=BOTTOM)
 
    def opt_def(self, opt):
        print 'You have choosen option', opt
 
    def opt_1(self):
        self.opt_def(1)

    def opt_2(self):
        self.opt_def(2)

root = Tk()
 
app = App(root)
 
root.mainloop()

Another way is to use the event:

# Tkinter, show the button that has been clicked
# using the bind event

import Tkinter as tk

def click(event):
    """
    event.widget.cget("text") gets the label
    of the button clicked
    """
    s = "clicked: " + event.widget.cget("text")
    root.title(s)

root = tk.Tk()
root.geometry("300x50+30+30")

b1 = tk.Button(root, text="button1")
b1.bind("<Button-1>", click)
b1.pack()

b2 = tk.Button(root, text="button2")
b2.bind("<Button-1>", click)
b2.pack()

root.mainloop()

Edited 5 Years Ago by bumsfeld: n/a

Actually simpler:

# Tkinter, show the button that has been clicked
# using lambda

from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        cmd1 = lambda: self.opt_def(1)
        self.opt1 = Button(frame, text="Opt1", command=cmd1)
        self.opt1.pack(side=TOP)

        cmd2 = lambda: self.opt_def(2)
        self.opt2 = Button(frame, text="Opt2", command=cmd2)
        self.opt2.pack(side=BOTTOM)

    def opt_def(self, opt):
        print 'You have choosen option', opt


root = Tk()

app = App(root)

root.mainloop()

Thanks for the replies. I've used lambda.

self.opt2 = Button(frame, text="Opt2", command=lambda: self.function(arguments))

This article has been dead for over six months. Start a new discussion instead.