gpt4 book ai didi

单击矩形时的python tkinter Canvas

转载 作者:行者123 更新时间:2023-12-01 12:23:10 27 4
gpt4 key购买 nike

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

这是代码:

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

关于单击矩形时的python tkinter Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42175815/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com