0

I'm trying to bind the items in my listbox to mouse button number 1 so that when i press it it prints "hi". However whenever i try to do it the code simply won't work. What happens is when i launch the program it will print "hi" once and then never again no matter how many times i click on the mouse button 1. Any suggestions? Thanks

            from tkinter import *

            class Applikation(Frame): 
                def __init__(self, master):

                    Frame.__init__(self,master)

                    self.master=master
                    self.rssList = Listbox(self.master, height=30, width=50) 
                    self.rssList.grid(row=1, column=0, rowspan=4, padx=10, pady=20)
                    self.rssList.bind("<Button-1>", print("hi"))


            rssReader = Tk()
            rssReader.title("Rss reader")
            rssReader.resizable(10, 10)
            app = Applikation(rssReader).grid()
            rssReader.mainloop()
MemeLord
  • 11
  • 2

2 Answers2

2

You need to pass the command as a reference without the () when binding to <Button-1>.

You can do so by either defining a separate function:

class Applikation(Frame):
    def __init__(self, master):
        ...
        self.rssList.bind("<Button-1>", self.print_hi)

    def print_hi(self,event):
        print ("hi")

Or use a lambda function:

self.rssList.bind("<Button-1>", lambda e: print("Hi"))
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • Thank you! Embarassing how long i tried to fix it without progress, maybe i'm just dumb cause looking it up didn't help, again, Thanks! – MemeLord Feb 17 '19 at 16:46
0

The print() function only prints to the console, not to the GUI.

The way I solved this was to make a new method for the Applikation class, and call that in in rssList.bind.

Meaning:

class Applikation(Frame): 
    def __init__(self, master):
        #everything else here is fine
        self.rssList.bind("<Button-1>", self.say_hi)

    def say_hi(self, default=None):
        self.rssList.insert(END, "Hi")
#Keep everything else here the same
RichAspden
  • 76
  • 1
  • 8