简体   繁体   English

如何使用绑定事件在组合框中立即打印文本?

[英]How can I print the text immediately in combobox with bind 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("<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. 例如,当我按a时,它什么都没有显示,然后按b。 It will show a, but not ab. 它将显示a,但不显示ab。 How can I fix this bug? 如何解决此错误? thanks. 谢谢。

You have it very close. 您已经非常接近了。 The bind statement is slightly different from what you need. bind语句与您所需要的稍有不同。 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 seems to figured-out and solved your issue. @Ron Norris似乎已解决并解决了您的问题。 Regardless, here's another way to do things that doesn't involve bind ing events, it uses the trace() method common to all Tkinter variable classes ( BooleanVar , DoubleVar , IntVar , and StringVar ) which is described here . 无论如何,这是另一种不涉及bind事件的处理方式,它使用所有Tkinter变量类( BooleanVarDoubleVarIntVarStringVar )通用的trace()方法, 此进行介绍 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM