Reputation: 571
I have read the answer to this question:
In Tkinter how to pass a called function as argument?
and while it seems related it does not appear to answer my question as the issue in the above question is with the user defined function being called. I am passing a called method (the .get() method of a tkinter StringVar) to the built in 'print' function. My code is as follows:
import tkinter as tk
from functools import partial
def print_called(variable):
print(variable.get())
try:
root = tk.Tk()
var = tk.StringVar()
options = tk.OptionMenu(root, var, 'string 1', 'string 2', 'string 3', 'string 4')
button_1 = tk.Button(root, text='button_1', command=partial(print_called, var))
button_2 = tk.Button(root, text='Button_2', command=partial(print, var.get()))
options.pack()
button_1.pack()
button_2.pack()
finally:
root.mainloop()
I run the above code and select 'string 1' from the menu. When I click button_1 it prints 'string 1' as expected. When I click button_2 it prints a blank line. My Questions are:
Upvotes: 0
Views: 84
Reputation: 2569
command=partial(print, var.get())
is evaluated directly when button_2
is created. At this point nothing is selected, and var.get()
returns an empty string.
You could use a lambda function: command=lambda: print(var.get())
, but this is almost the same as what you did in button_1
, just with a lambda function instead of a normal one.
Upvotes: 1