Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

Need to press key twice after exception - Python tkinter

newbie here.

I'm using tkinter for this.

In below code label text immediately updates when key 1, 2 or 3 is pressed. When another regular key (like 'k' or '5') is pressed before, it also immediately updates.

But, now the problem: when a special key (like Alt) is pressed before, it only updates when first any key is pressed, and then 1, 2 or 3. Like you need to press twice after a special key is pressed.

In code below try/except is used to ignore ValueError of special key input.

What I want is that the label text always immediately updates no matter what key is pressed before.

Please share how to do this, thanks!

from tkinter import *

def getKey(event):
    
    userIn=''
    
    try:
        
        if event.char in '1 2 3':
            userIn = event.char 
            l['text'] = userIn
            
    except:
        pass    
    

root = Tk()
l = Label(root, text='input')
l.pack()
root.bind('<Key>', getKey)

root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use <KeyRelease> instead of <Key> (which is the same as <KeyPress>).

Also event.char in '1 2 3' is True when event.char is either '1', '2', '3', ' ' and empty string. So pressing special key (which cause event.char is empty) will clear the text. Use event.char in ['1','2','3'] instead.

from tkinter import *

def getKey(event):
    if event.char in ['1', '2', '3']:
        l['text'] = event.char
    
root = Tk()

l = Label(root, text='input')
l.pack()

root.bind('<KeyRelease>', getKey)
root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...