Tkinter - pass argument to function

Asked

Viewed 241 times

0

I have the following code:

class Tela:
    def __init__(self, master=None):
        self.fontePadrao = ("Arial", "10")
        master = Toplevel(self.root)
        self.primeiroContainer = Frame(master)
        self.primeiroContainer["pady"] = 10
        self.primeiroContainer["padx"] = 30
        self.primeiroContainer.pack()

        self.segundoContainer = Frame(master)
        self.segundoContainer["pady"] = 10
        self.segundoContainer.pack()

        self.titulo = Label(self.primeiroContainer, text="Client")
        self.titulo["font"] = ("Arial", "10", "bold")
        self.titulo.pack()

        self.btnMessage = Button(self.segundoContainer)
        self.btnMessage.pack(side=LEFT)
        self.btnMessage["text"] = "imprimir mensagem"
        self.btnMessage["font"] = ("Calibri", "10")
        self.btnMessage["width"] = 15
        self.btnMessage["command"] = self.printMessage("Olá!")
        self.btnMessage.pack()

    def printMessage(message):
        print(message)

But I can’t get the argument to function... as I should?

  • Which function you refer to?

  • I refer to printMessage function()

  • She’s a method, so she shouldn’t get self as first parameter, just as you did in __init__?

  • Oops, I’ve seen it now too, and fixed it. But my problem here is that the way it is, when the program runs it already calls this function. But I want it to be called only when I click the button. Without passing the parameters and leaving a message sinking there, it works. ai at the time of calling her by the button, I put only printMessage, without the parentheses.

2 answers

1

You did

self.btnMessage["command"] = self.printMessage("Olá!")

Which is basically attributing the return of function self.printMessage as command. Since it has no return, the value will be assigned None. However, you are expected to pass as a command a calling object and the idea is that when this object is called the message is displayed.

To do this, you can use the function functools.partial that creates a new calling object and that you can define the values of the parameters:

from functools import partial

...
self.printMessage = partial(self.printMessage, "Olá!")

Thus, the return of partial(self.printMessage, "Olá!") will be a calling object that when called will execute the function self.printMessage passing to string "Olá!" as a parameter.

0

I managed to solve the problem. putting a lambda on the line

self.btnMessage["command"] = lambda: self.printMessage("Olá!")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.