【问题标题】:Tkinter binding combination of key and mouseTkinter 键鼠绑定组合
【发布时间】:2021-05-16 22:23:21
【问题描述】:

我是 tkinter 的新手,现在正在处理键或鼠标点击的绑定功能。我试图通过按住键盘上的一个键然后按下 Button-1 来触发一个功能。使用“”进行绑定不起作用。请帮忙。

class PyViz:
    def __init__(self):
        self.window = Tk()
        self.window.geometry("1000x500")
        self.frame = Frame(self.window, width=2000, height=1000)
        self.frame.pack(expand=True, fill=BOTH)

        self.canvas = Canvas(
            self.frame,
            width=2000,
            height=1000,
            bg="#FAE6FA",
            scrollregion=(0, 0, 1000, 1000),
        )

        self.motion = Motion(
            window=self.window,
            canvas=self.canvas,
            boxes=self.boxes,
            connections=self.connections,
        )

        self.bind_keys()

        self.window.mainloop()

    def bind_keys(self):
        self.window.bind("c <Button-1>", self.motion.add_class_with_click)
        self.window.bind("<KeyPress-c> <a>", self.motion.add_class)

class Motion:
    def __init__(self, window, canvas, boxes, connections) -> None:
        self.window = window
        self.canvas = canvas
        self.boxes = boxes
        self.connections = connections

    def add_class(self, event):
        """
        green rectangle
        """

        rect_uuid = str(uuid.uuid4())
        new_rect = Box(color="#98FB98", pos=(10, 10), id=rect_uuid)
        new_rect.create_box(self.canvas)
        self.boxes["class"].setdefault(rect_uuid, new_rect)
        print(self.boxes)

    def add_class_with_click(self, event):
        """
        green rectangle
        """
        print("pressed")
        self.add_class(event)

    def add_method(self):
        """
        orange rectangle
        """
        pass

这是我正在处理的代码。我正在尝试将键 c 和 button-1 绑定到一个函数。答案的示例在我运行时有效,但由于某种原因,该解决方案在此处使用时不起作用。

【问题讨论】:

标签: tkinter bind


【解决方案1】:

要绑定多个键,请按顺序一次指定一个。

例如,绑定“a”键然后单击按钮,您将执行root.bind("a &lt;Button-1&gt;", func)

在您的问题中,您想绑定任意键+鼠标单击。为此,请使用root.bind("&lt;Key&gt; &lt;Button-1&gt;"):

from tkinter import *


def pressed(a):
    print("Pressed")


root = Tk()

root.bind("<Key> <Button-1>", pressed)
root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多