0

Good day everyone. I've been baffled dealing with my python code. Im using Tkinter for my GUI for our individual school project.

I have this code as a window (for my Create menu in menu bar in main.py) on another file (let's say functions.py):

def createNew(coord):
    #create a new window element
    createWindow = tk.Tk()
    createWindow.title("Create a new tracker")
    createWindow.geometry("350x400")

    createWindow.focus_force()
    createWindow.grab_set()

    x = coord[0]
    y = coord[1]

    createWindow.geometry("+%d+%d" % (x + 250, y + 200))

The above code has that coord argument which receives the input from main.py with this code (the functions.py is imported as funct):

parentPosition = [window.winfo_x(), window.winfo_y()]
...
menubar = tk.Menu(window)
#file menu
file = tk.Menu(menubar, tearoff=0)
file.add_command(label='Create new tracker', command=funct.createNew(parentPosition))

My problem is that whenever I execute the main.py, this window from functions.py automatically shows up even though I didn't select the Create menu from main.py. The intended location is correct anyway.

Actual snapshot of the UI

What is the issue within my code? Any insights would be appreciated.

PS. I intentionally put the function createNew in functions.py rathen than on main.py

1 Answers1

0

You execute the function immediately when you run the line

file.add_command(label='Create new tracker', command=funct.createNew(parentPosition))

This is because, by putting a pair of brackets after the function name, you call it right away, and pass its return value to the add_command function.

In order to get around this, you can use the lambda keyword to delay execution of the function until it is called again:

file.add_command(label='Create new tracker', command=lambda: funct.createNew(parentPosition))

You can find out more about lambda functions here.

Lecdi
  • 2,189
  • 2
  • 6
  • 20