【问题标题】:python tkinter canvas when rectangle clicked单击矩形时的python tkinter画布
【发布时间】:2017-06-29 18:31:04
【问题描述】:

当我单击 tk 画布上的矩形时,我一直在尝试使函数运行。

代码如下:

from tkinter import *

window = Tk()

c = Canvas(window, width=300, height=300)

def clear():
    canvas.delete(ALL)

playbutton = c.create_rectangle(75, 25, 225, 75, fill="red")
playtext = c.create_text(150, 50, text="Play", font=("Papyrus", 26), fill='blue')

c.pack()

window.mainloop()

有人知道我应该怎么做吗?

【问题讨论】:

  • 你试过用画布bind方法吗?
  • 看看.tag_bind方法here

标签: python tkinter tkinter-canvas


【解决方案1】:

您可以在要绑定事件的项目上添加标签。
你想要的事件是<Button-1>,也就是鼠标左键。
要将其应用于您的示例,您可以这样做:

from tkinter import Tk, Canvas

window = Tk()

c = Canvas(window, width=300, height=300)

def clear():
    canvas.delete(ALL)

def clicked(*args):
    print("You clicked play!")

playbutton = c.create_rectangle(75, 25, 225, 75, fill="red",tags="playbutton")
playtext = c.create_text(150, 50, text="Play", font=("Papyrus", 26), fill='blue',tags="playbutton")

c.tag_bind("playbutton","<Button-1>",clicked)

c.pack()

window.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-11
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2017-10-21
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多