0

I am trying to learn making a GUI using python. I am trying to use a menu system to then have one of the menu options call a function to update the GUI. However instead of when pressing the menu option the GUI updates the GUI is already calling the function on launch.

Heres is my current code.

import tkinter as tk
from tkinter import *
root = tk.Tk()

def db_insert():
    Label(root,text='Item Name: ').grid(row=0)
    Label(root,text='Item Cost: ').grid(row=1)
    Label(root,text='Item Quantity: ').grid(row=2)
    e1 = Entry(root)
    e2 = Entry(root)
    e3 = Entry(root)
    e1.grid(row=0,column=1)
    e2.grid(row=1,column=1)
    e3.grid(row=2,column=1)

menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File',menu=filemenu)
filemenu.add_command(label='Insert',command=db_insert())
filemenu.add_separator()
filemenu.add_command(label='Exit',command=root.quit)

root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Cwsager
  • 3
  • 1
  • 1
    `command=db_insert()` calls the function *right now*, and uses its return value (probably `None`) as the command to execute when the button is clicked. You don't want those parentheses here. – jasonharper Jun 04 '20 at 22:32

1 Answers1

0

As @jasonharper said, you don't want the parenthesis when passing a function for a callback, like you did with your exit command command.

import tkinter as tk

root = tk.Tk()

def db_insert():
    tk.Label(root,text='Item Name: ').grid(row=0)
    tk.Label(root,text='Item Cost: ').grid(row=1)
    tk.Label(root,text='Item Quantity: ').grid(row=2)
    e1 = tk.Entry(root)
    e2 = tk.Entry(root)
    e3 = tk.Entry(root)
    e1.grid(row=0, column=1)
    e2.grid(row=1, column=1)
    e3.grid(row=2, column=1)

menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='Insert', command=db_insert) # <-- Removed parenthesis
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)

root.mainloop()
Unsigned_Arduino
  • 357
  • 2
  • 16