Home > Enterprise >  Why can't I call function within tkinter bind?
Why can't I call function within tkinter bind?

Time:10-25

I am doing a project using tkinter and I stumbled upon this problem. When i try to call the bind function to open my numeric keyboard when I click on entry widget I get this error.

Traceback (most recent call last):
File "test.py", line 40, in <module>
app = Main()
File "test.py", line 15, in __init__
self.main_frame()
File "test.py", line 28, in main_frame
eF.bind("<1>", open_numeric_keyboard(0))    #open numeric for feedrate
NameError: name 'open_numeric_keyboard' is not defined

I have the same problem even if i try to call different functions or some from libraries. The rest of the code is working just fine so here is kind of a short cut from the main code with the part that is causing problems.

from tkinter import *


class Main:
    def __init__(self):
        self.entry_widget = 0

        self.root = Tk()
        self.root.resizable(width=False, height=False)
        self.root.geometry("800x480")
        self.width = 480
        self.height = 480

        self.main_frame()


    def main_frame(self):
        self.f_main = Frame(self.root, height = 480, width = 320, borderwidth = 1, highlightbackground="red",highlightthickness=1)
        self.f_main.place(x=480, y=0)

        eF = Entry(self.f_main, relief = "groove")
        eMM = Entry(self.f_main, relief = "groove")

        eF.place(x = 70, y = 127, height = 40, width = 60)
        eMM.place(x = 70, y = 166, height = 40, width = 60)

        eF.bind("<1>", open_numeric_keyboard(0))    #open numeric for feedrate
        eMM.bind("<1>", open_numeric_keyboard(1))   #open numeric for MM

    def open_numeric_keyboard(self, entry):
        self.numeric_frame.tkraise()
        if entry == 0:      #F
            self.entry_widget = 0

        elif entry == 1:    #MM
            self.entry_widget = 1

app = Main()

CodePudding user response:

It's self.open_numeric_keyboard, just like you're already doing self.main_frame() (which should be named e.g. create_self_frame if you ask me).

Then, you'll need to wrap the function in a lambda so it doesn't get immediately invoked:

eF.bind("<1>", lambda *_args: self.open_numeric_keyboard(0))
eMM.bind("<1>", lambda *_args: self.open_numeric_keyboard(1))
  • Related