Ivar Eriksson
Ivar Eriksson

Reputation: 973

Tkinter, calling a function with arguments

I've recently finished a simple command line Othello game and am now trying to create a GUI for it. My thought was that I would press a frame in an 8 by 8 grid and that that would call my place_tile function (method) with the frames coordinates. I've been able too call functions that require arguments with buttons but I'm having issues when it comes to frames. Does anyone have an idea what I'm doing wrong or maybe a better way for my to do it?

Example code that works:

from tkinter import *

root = Tk()
def hello(word):
    print(word)

def bye(event):
    print("Bye")

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", bye)
button = Button(root, text="Bye", command=lambda:hello("Hi"))
button.pack()
background.pack()
root.mainloop()

What I want to do is call something like the hello function from a frame like background, thanks.

Upvotes: 2

Views: 1314

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90869

You can use default arguments to the lambda function , Example -

def dummy(frameobj):
    pass

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", bye)
button = Button(root, text="Bye", command=lambda frameobj=background:hello(frameobj))

When the lambda would be called, it would be called without any arguments, so the default values that were specified would be used.


If you want to pass arguments to functions used in bind() , then you need to also include event argument that is automatically passed by tkinter. Example -

def bye(event, frameobj):
    print("Bye")

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", lambda event, frameobh=background: bye(event,frameobj))

But all you want is the Frame object from which the bye() method was called , you can easily get that using the event variable that is passed by tkinter - event.widget . Example -

def bye(event):
    frameobj = event.widget
    print("Bye")

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", bye)

Upvotes: 1

Related Questions