当我点击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()
有谁知道我应该做什么?
答案 0 :(得分: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()