【问题标题】:Tkinter mouse and key press at the same timeTkinter 鼠标和按键同时按下
【发布时间】:2019-03-18 03:36:31
【问题描述】:

我正在尝试从 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) 注册按键,但我不确定如何同时获取两者,因为按钮事件不会通过按键

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    不确定是否有官方方法可以同时绑定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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 2021-04-20
      • 2020-04-28
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2011-06-17
      • 2013-06-07
      相关资源
      最近更新 更多