0
            from tkinter import *
            from tkinter.ttk import *

            month  = (1,2,3,4,5,6,7,8,9,10,11,12)

            def func1(self,event = None):
                var = self.CB1.get()
                print(var)
                print("Your Birthday is: " + var)


            class app():
                def __init__(self):

                    window = Tk()


                    self.CB1 = Combobox(window,values = month,state = "readonly")
                    self.CB1.current(0)

                    self.CB1.bind("<<ComboboxSelected>>", func1(self,event = None))

                    self.CB1.pack()

                    window.mainloop()


            app()

So it will output 1, and say "Your birthday is 1", it will not do it again if I select a different number. I have tried over 10 different pages to understand combo-boxes, and am failing quite hard to understand. Any help would be appreciated. Thank you to all who help.

Martelmungo
  • 42
  • 1
  • 8

2 Answers2

2

This happens because in the line

self.CB1.bind("<<ComboboxSelected>>", func1(self,event = None))

func1 is executed directly and the result (None) is assigned as the bind "function". Use a lambda expression like this:

self.CB1.bind("<<ComboboxSelected>>", lambda x: func1(self, x))

Now you're binding an anonymous function to the event without executing it.

TidB
  • 1,749
  • 1
  • 12
  • 14
1

The @TidB answer about lambda function and why your combobox runs only once is absolutely correct!

But I'm confused by how you built your class and how you passed self and event outside the class. Is it really what you want or are you trying to do something like this?

try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

month = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

class App():
    def __init__(self):
        window = tk.Tk()

        self.CB1 = ttk.Combobox(window, values=month, state="readonly")
        self.CB1.current(0)
        self.CB1.bind("<<ComboboxSelected>>", self.func1)
        self.CB1.pack()

        window.mainloop()

    def func1(self, event=None):
        var = self.CB1.get()
        print(var)
        print("Your Birthday is: " + var)

App()

Python passes your self and event for you implicitly, so why're you trying to do a same job? So I think that a real problem stems from your class's structure. And this is a real cause why your combobox runs only once.

Community
  • 1
  • 1
CommonSense
  • 4,232
  • 2
  • 14
  • 38