Sid
Sid

Reputation: 151

How to pass parameters to functions in python

I have this simple program that I wrote so I could better understand the 'return' function and how to pass a value from one function to another. All this program does is to pass the value of buttontwo=2 to the function button_one_function,so if button two is pressed first then button one does nothing.I thought that I could do this without using a global statement - is there a way of writing the code below without using global? I have tried doing this by putting the value of buttontwo in to the button_one_function parentheses but this didnt work. Thanks for any tips

from tkinter import *

my_window = Tk()

my_frame = Frame(my_window, height=500, width=500, bd='4')

my_frame.grid(row=0, column=0)


def button_one_function():
    if button_two == 2:
        print('do nothing')
    else:
        label_one = Label(my_frame, text='label one')
        label_one.grid(row=1, column=0, sticky='n')


def button_two_function():
    global button_two
    button_two = 2
    label_two = Label(my_frame, text='label two')
    label_two.grid(row=1, column=1, sticky='n')
    return button_two


button_one = Button(my_frame, text='button1', command=button_one_function)
button_one.grid(row=0, column=0)

button_two = Button(my_frame, text='button2', command=button_two_function)
button_two.grid(row=0, column=1)

my_window.mainloop()

Upvotes: 0

Views: 247

Answers (3)

PythonAmateur742
PythonAmateur742

Reputation: 334

You can definitely do this without globals. You could extend the tk.button class to hold a variable like self.status = pressed.

There are a few ways you can go about this with classes. You could create either one or two classes. Maybe even have child classes for each button.

But you can just dump both your functions in one class and pass self as its first argument.

Whenever I feel the need for a global variable, I usually make a class.

Upvotes: 0

rizerphe
rizerphe

Reputation: 1390

If I've understood corectly, you are interested in sth. like this:

from tkinter import *

root = Tk()

def click(a):
    print(a)

Button(root, text='1', command=lambda: click('1')).pack()
Button(root, text='2', command=lambda: click('2')).pack()

root.mainloop()

What is happening is I'm not passing a full click function to a button, but a so called lambda function, which is essentially a one-line function. Example: if I did p = lambda: print('Hi') then each time I do p() I would see a little Hi pop up. Also, if I did k = lambda a,b: a*b then k(4,5) would return "20". More info about lambdas here. Hope that's helpful!

Upvotes: 1

Anuradhe Dilshan
Anuradhe Dilshan

Reputation: 102

def function(a,b):
print("a is :",a)
print("b is :",b)


function(10,20)

Upvotes: 0

Related Questions