-1

I've been fiddling with this snippet for producing a grid of tkinter Entry widgets. When I write the code like this, it works as intended:

import tkinter as tk

rows = []
for i in range(5):
    cols = []
    for j in range(4):
        e = tk.Entry()
        e.grid(row=i, column=j, sticky="nsew")
        e.insert("end", '%d.%d' % (i, j))
        cols.append(e)
    rows.append(cols)

def onPress():
    for row in rows:
        for col in row:
            print (col.get())


tk.Button(text='Fetch', command=onPress).grid()
tk.mainloop()

But if its like this, it runs the command "onPress" before the button is pressed:

import tkinter as tk
def entries():
    rows = []
    for i in range(5):
        cols = []
        for j in range(4):
            e = tk.Entry()
            e.grid(row=i, column=j, sticky="nsew")
            e.insert("end", '%d.%d' % (i, j))
            cols.append(e)
        rows.append(cols)
    return rows

def onPress(rows):
    for row in rows:
        for col in row:
            print (col.get())

entries()
tk.Button(text='Fetch', command=onPress(entries())).grid()
tk.mainloop()

Why is this happening? It looks to me like these should be equivalent. I'm a beginner, so I'm probably missing something very obvious.

  • 1
    Possible duplicate: [Why is Button parameter “command” executed when declared? \[duplicate\]](https://stackoverflow.com/q/8269096/953482) – Kevin Feb 15 '19 at 14:50

1 Answers1

0

onPress(entries()) in tk.Button(text='Fetch', command=onPress(entries())) calls onPress immediately, but command=onPress in tk.Button(text='Fetch', command=onPress) passes a function called onPress as an argument.

ForceBru
  • 43,482
  • 10
  • 63
  • 98