Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emit events in tkinter?

I have simple app written in python3 and tkinter module. I want to write my custom widget and need to send my custom event.

Why this sample code below does not work?

#!/usr/bin/env python3

from tkinter import *

class MyWidget(Listbox):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)

        # ===================
        # error:  _tkinter.TclError: only one event specification allowed
        self.bind('<<ListboxSelect>>', lambda e: self.event_generate('MyEvent'))
        # ===================


class App(Tk):
    def __init__(self):
        super().__init__()
        w = MyWidget(self)
        w.bind('MyEvent', lambda e: print('It\'s working'))
        w.pack()

        w.insert(END, 'ddddddd')


if __name__ == '__main__':
    app = App()
    app.mainloop()
like image 441
BPS Avatar asked Jan 03 '23 02:01

BPS


1 Answers

Virtual events need to be surrounded by << and >>. Just replace 'MyEvent' by '<<MyEvent>>' and your custom event should work.

like image 98
j_4321 Avatar answered Jan 05 '23 16:01

j_4321