import tkinter as tk
from tkinter import ttk
def button_func():
print(string_var.get())
# window
window = tk.Tk()
window.title('Tkinter Variables')
# tkinter variable
string_var = tk.StringVar()
# widgets
label = ttk.Label(master=window, text='label', textvariable=string_var)
label.pack()
entry = ttk.Entry(master=window, textvariable=string_var)
entry.pack()
button = ttk.Button(master=window, text='button', command=button_func())
button.pack()
# run
window.mainloop()
I saw the fix of remove the parentheses, it work but really confused me. New to python and tkinter, not sure is that the correct fix or some sort of mess up.
button = ttk.Button(master=window, text='button', command=button_func)
The problem here has indeed to do with "adding or removing parentheses"
All that is needed for your code to work is not to put parentheses on the call that creates the Button
:
button = ttk.Button(master=window, text='button', command=button_func)
When you add a parentheses pair and do button_func()
, that is just an ordinary function call - Python resolves it immediately: just call the function at this point, which is before the call to instantiate the Button itself - want is passed as the command
argument is what is returned by the button_func (which, as it does not have a return
statement is a None
value).
When the parentheses are left out, which is the correct code, the function itself is passed as the command to be called back to tkinter.