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:
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
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!