The*_*Pig 10 python tkinter tkinter-canvas
当我单击 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()
Run Code Online (Sandbox Code Playgroud)
有谁知道我应该做什么?
el3*_*ien 16
您可以在要绑定事件的项目上添加标签。
您在这里想要的事件<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()
Run Code Online (Sandbox Code Playgroud)