tk_pass_args_to_callback.py

# =========================================================
# Test:
# 1. what type is the resulting b1 or b2 variables
# 2. how to passing paramerters to button (or any widget)
#    event callback
# ---------------------------------------------------------
# What happens? Why? Name of the callback function?
# ---------------------------------------------------------
# How to test:
#   test 1: run code as is
#   test 2: switch button creation code (see ## in the code)
# =========================================================
# Passing Argument to Callbacks. If you do this, Python
# will call the callback function before creating the
# widget, and pass the function's return value to Tkinter.
# Tkinter then attempts to convert the return value to a
# string, and tells Tk to call a function with that name
# when the button is activated.
# =========================================================

# --- import ----------------------------------------------

import sys

if sys.version_info.major == 3:
    from tkinter import *
else:
    from Tkinter import *

# --- functions -------------------------------------------

##def quit():
##    sys.exit()

def quit(arg):
    print('quit callback received {}'.format(arg))
    sys.exit()

# --- main ------------------------------------------------

root = Tk()

##b1 = Button(root, text='B1', command=quit).grid(row=0, column=0)
##b1 = Button(root, text='B1', command=quit('B1')).grid(row=0, column=0)
b1 = Button(root, text='B1',
        command=lambda: quit('B1')).grid(row=0, column=0)

print('B1 type: {}'.format(type(b1)))

##b2 = Button(root, text='B2', command=quit)
##b2 = Button(root, text='B2', command=quit('B2'))
b2 = Button(root, text='B2',
        command=lambda: quit('B2'))
b2.grid(row=0, column=1)

print('B2 type: {}'.format(type(b2)))

root.mainloop()