tkinter同时使用两个键 [英] tkinter using two keys at the same time

查看:140
本文介绍了tkinter同时使用两个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,tkinker一次只能使用一个键. 在这个例子中,我不能说同时向左和向上移动. 如果愿意,我将如何去做?

So tkinker can only use one key at a time. I am unable to say move to the left and up at the same time with this example. How would i go about doing it if I wanted to?

import tkinter
root = tkinter.Tk()
root.title('test')
c= tkinter.Canvas(root, height=300, width=400)
c.pack()
body = c.create_oval(100, 150, 300, 250, fill='green')

def key(event):
    OnKeyDown(event.char)
    print(event.char)

def MoveLeft(evenr)
    c.move(body, -10, 0)

def MoveRight(event):
    c.move(body, 10, 0)

def MoveUp(event):
    c.move(body, 0, 10)

def MoveDown(event):
    c.move(body, 0, -10)

root.bind('<KeyPress-Left>', MoveLeft)
root.bind('<KeyPress-Right>', MoveRight)
root.bind('<KeyPress-Up>', MoveUp)
root.bind('<KeyPress-Down>', MoveDown)

就个人而言,我也不想不必将我的按键绑定"到功能上,我也想使用这些按键来执行其他操作(即:如果我同时按住shift键并向上移动,则使其移动得更快.时间)可以修补匠识别出您预先分配两个键或同时按住两个键吗?

Personally I would also prefer to not have to "bind" my keys to functions as well as I also would like to use the keys to preform other actions (ie: make it move faster if I hold shift and up at the same time) Can tinker recognize when you pre-assign two keys or hold two keys at the same time?

推荐答案

就像这样:

from Tkinter import *

root = Tk()
var = StringVar()
a_label = Label(root,textvariable = var ).pack()

history = []
def keyup(e):
    print e.keycode
    if  e.keycode in history :
        history.pop(history.index(e.keycode))

        var.set(str(history))

def keydown(e):
    if not e.keycode in history :
        history.append(e.keycode)
        var.set(str(history))

frame = Frame(root, width=200, height=200)
frame.bind("<KeyPress>", keydown)
frame.bind("<KeyRelease>", keyup)
frame.pack()
frame.focus_set()
root.mainloop()

这篇关于tkinter同时使用两个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆