user1967718
user1967718

Reputation: 1005

How to set function parameter with Button in Tkinter?

I´d like to create a function, which will take it´s parameter from Button click. For instance:

from Tkinter import *

def func(b):
    number = 2*b
    print number
    return

root=Tk()

# By clicking this button I want to set b = 1 and call func

b1 = Button(root,...)
b1.pack()

# By clicking this button I want to set b = 2 and call func

b2 = Button(root,...)
b2.pack()

root.mainloop()

So after clicking b1, "number" should be 2 and after clicking b2, "number" should be 4.

I hope I explained my problem well.

Thanks for answers

mountDoom

Upvotes: 0

Views: 1284

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

Here's one way

from sys import stderr
from Tkinter import *

def func(b):
    number = 2*b
    stderr.write('number=%d\n'%number)
    return

root=Tk()

# By clicking this button I want to set b = 1 and call func

b1 = Button(root,command=lambda : func(1))
b1.pack()

# By clicking this button I want to set b = 2 and call func

b2 = Button(root,command=lambda : func(2))
b2.pack()

root.mainloop()

Upvotes: 4

Related Questions