1
from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<Key>", print1)
combobox1.focus_set()
combobox1.pack()


mainloop()

How can I fix the problem that is, when I press the first button, it didn't show immediately.
For example, when I pressed a, it didn't show anything, and then I pressed b. It will show a, but not ab. How can I fix this bug? thanks.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
Tony
  • 13
  • 2

2 Answers2

2

You have it very close. The bind statement is slightly different from what you need. The problem was that it was printing before the key was delivered to the combobox. Now it waits until the key is released to fire the event.

from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<KeyRelease>", print1)
combobox1.focus_set()
combobox1.pack()


mainloop()
Ron Norris
  • 2,642
  • 1
  • 9
  • 13
0

@Ron Norris seems to figured-out and solved your issue. Regardless, here's another way to do things that doesn't involve binding events, it uses the trace() method common to all Tkinter variable classes (BooleanVar, DoubleVar, IntVar, and StringVar) which is described here. The arguments it receives when called are explained in the answer to this question.

from Tkinter import *
import ttk

main=Tk()

def print1(*args):
    string = combobox1.get()
    print string

val = StringVar()
val.trace("w", print1)  # set callback to be invoked whenever variable is written

combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.focus_set()
combobox1.pack()

mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301