Tkinter鼠标和按键同时

时间:2019-03-18 03:36:31

标签: python tkinter

我正在尝试从pygame转换为tkinter,因为它似乎比我想做的要好得多,尽管我遇到了一些困难。同时按下某个键和鼠标按钮时,我需要能够调用一个函数。在pygame中,它很简单,如下所示。

while not done:
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()
        mouse = pygame.mouse.get_pressed()
        if event.type == pygame.QUIT:
            done = True

        if mouse[0]:
            if keys[pygame.K_s]:
                pos = pygame.mouse.get_pos()
                // function 

我知道在tkinter中,您可以执行c.bind("<Button-1>", function)来注册鼠标单击,而c.bind("e", function)来注册按键,但是由于按钮事件没有通过,因此我不确定如何同时获得两者通过按键

1 个答案:

答案 0 :(得分:0)

不确定是否有绑定Button-1Key的正式方法,但是也许您可以解决它。

import tkinter as tk

root = tk.Tk()

tk.Label(root,text="Hi I'm a label").pack()

class Bindings:
    def __init__(self):
        self.but_1 = False
        root.bind("<Button-1>", self.mouse_clicked)
        root.bind("<e>", self.e_clicked)
        root.bind("<ButtonRelease-1>",self.mouse_release)

    def mouse_release(self,event):
        self.but_1 = False

    def mouse_clicked(self,event):
        self.but_1 = True
        print ("Mouse button 1 clicked")

    def e_clicked(self,event):
        if self.but_1:
            print ("Both keys clicked")
            self.but_1 = False
        else:
            print ("Key E pressed")

Bindings()
root.mainloop()
相关问题