2017-02-11 138 views
0

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

下面是代码:

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

你试图使用画布'bind'方法? –

+0

查看'.tag_bind'方法[here](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/canvas-methods.html) –

回答

0

您可以在要将事件绑定到的项目上添加标签。
您想要的事件是<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()