[PYTHON] When you want to save the result of the callback function somewhere

Problems encountered when creating a Tkinter GUI app How can I save the processing result of the callback function called by the bind method? (= User operation such as mouse triggers as an event and calls a callback function)

The procedure is as follows:

  1. Define a class that saves the processing result in the form of an instance variable
  2. Create one object based on the class defined in step 1.
  3. Pass the class object from step 2 to the callback function when calling the bind method
  4. Set the processing result for the class object of the argument passed in the callback function

In the sample code below, after the Tkinter GUI window is displayed, The bind method calls a callback function called b1Pressed each time the left mouse button is clicked. In addition to the event (e) itself, specify a class object called obj1 as an argument passed to b1Pressed in the form of a lambda function. b1Pressed adds 1 to obj1.var_hoge each time it is called and saves the processing result in obj1.var_hoge

guiTest.py


import tkinter as tk
from tkinter import ttk
import PIL
from PIL import Image,ImageTk

root = tk.Tk()
root.title('hoge')
root.minsize(796,816)

#Loading images
img = PIL.Image.open(r"C:\Users\User\Desktop\experiment\a.png ")
im = PIL.ImageTk.PhotoImage(img)

#Mouse click event handler
def b1Pressed(e, obj1):
        print("b1Pressed has been called!")
        obj1.var_hoge += 1
        print("var_hoge"+ str(obj1.var_hoge))
#Class for storing the processing result of the variable performed by the callback function
class storeVar():
    def __init__(self):
        self.var_hoge = 0

#Canvas settings
cvs = tk.Canvas(bg="black", width=796, height=816)
cvs.place(x=0, y=0)
cvs.create_image(0,0,image=im, anchor=tk.NW)

#Prepare a class object
obj1 = storeVar()

#Call the event handler when the mouse button is pressed
cvs.bind("<ButtonPress-1>", lambda event, arg=obj1:b1Pressed(event, arg))
root.mainloop()

The processing result is as follows (result of clicking the left mouse button four times)

guiTest.Execution result of py


b1Pressed has been called!
var_hoge is 1!
b1Pressed has been called!
var_hoge is 2!
b1Pressed has been called!
var_hoge is 3!
b1Pressed has been called!
var_hoge is 4!

Recommended Posts

When you want to save the result of the callback function somewhere
When you want to update the chrome driver.
Python Note: When you want to know the attributes of an object
I want to grep the execution result of strace
I want to get the name of the function / method being executed
When you want to keep the Sphinx documentation theme as usual
When you want to adjust the axis scale interval with APLpy
When you want to use multiple versions of the same Python library (virtual environment using venv)
Memorandum of means when you want to make machine learning with 50 images
Python: I want to measure the processing time of a function neatly
I want to display the number of num_boost_rounds when early_stopping is applied using XGBoost callback (not achieved)
I want to customize the appearance of zabbix
I want to use the activation function Mish
[Python] I want to know the variables in the function when an error occurs!
Defense Techniques When You Have to Fight the Performance of Unfamiliar Applications (Part 2)
What you want to memorize with the basic "string manipulation" grammar of python
Linux: Netplan configuration guide to see when you want to fix the IP address
I want to store the result of% time, %% time, etc. in an object (variable)
[Python3] Code that can be used when you want to change the extension of an image at once
Create a function to visualize / evaluate the clustering result
Settings when you want to run python-mecab with travis
A convenient function memo to use when you want to enter the debugger if an error occurs when running a Python script.
When you want to filter with Django REST framework
When you want to play a game via Proxy
Specifies the function to execute when the python program ends
Measures to be taken when garbled characters when trying to redirect / pipe the result of aws-cli
When the variable you want to superscript with matplotlib is two or more characters
How to hit the document of Magic Function (Line Magic)
When you want to plt.save in a for statement
When you think the update of ManjaroLinux is strange
The programming language you want to be able to use
I want to increase the security of ssh connections
I want to be notified of the connection environment when the Raspberry Pi connects to the network
Make a note of what you want to do in the future with Raspberry Pi
[Python] When you want to import and use your own package in the upper directory
If you want to put an argument in the closure function and execute it later
Solution when you want to use cv_bridge with python3 (virtualenv)
[Django] A memorandum when you want to communicate asynchronously [Python3]
[AWS] What to do when you want to pip with Lambda
Try to get the function list of Python> os package
I want to save the photos sent by LINE to S3
I want to use only the normalization process of SudachiPy
Use aggdraw when you want to draw beautifully with pillow
I made a function to check the model of DCGAN
How to run the Export function of GCP Datastore automatically
I want to judge the authenticity of the elements of numpy array
When you want to register Django's initial data with relationships
I want to know the features of Python and pip
When you want to use python2.x on modern Gentoo Linux
If you want your colleagues to use the same language
I tried to fight the Local Minimum of Goldstein-Price Function
Keras I want to get the output of any layer !!
I want to know the legend of the IT technology world
When you want to hit a UNIX command on Python
Scraping the result of "Schedule-kun"
What is the Callback function?
[Django] What to do if the model you want to create has a large number of fields
[Django] Carefully explain the escape route if you really want to use the table of another application
[Subprocess] When you want to execute another Python program in Python code
I want to manually assign the training parameters of the [Pytorch] model
I want to save the trouble of inputting when debugging Paiza's skill check example in a local environment such as Jupyter [Python]