gpt4 book ai didi

python - 绑定(bind)/事件给出错误 'int' 对象没有属性 'bind'

转载 作者:行者123 更新时间:2023-12-01 04:47:19 24 4
gpt4 key购买 nike

我试图了解绑定(bind)和事件在 python 中如何工作。例如,我创建了 3 个图 block ,希望能够更改其中一个图 block 的颜色,但无法理解或弄清楚我哪里出错了。我不断得到:

AttributeError: 'int' object has no attribute 'bind'.

下面是代码并提前致谢:

import tkinter

def main():

root = tkinter.Tk()

title = tkinter.Label(root, text="Test Window")
title.pack()


canvas= tkinter.Canvas(root, background='green', width = 300, height = 300)

tile1=canvas.create_rectangle(0, 0, 100, 100, fill = 'magenta')
tile2=canvas.create_rectangle(100,0, 200,100, fill = 'blue')
tile3=canvas.create_rectangle(200,0, 300,100, fill = 'blue')

canvas.pack()

def change_square(event):
event.configure(background = 'blue')

tile1.bind("<Button-1>", change_square(tile1))

root.mainloop()

if __name__ == '__main__':
main()

最佳答案

itemconfigure 将更改颜色:

def main():
root = tkinter.Tk()

title = tkinter.Label(root, text="Test Window")
title.pack()

canvas = tkinter.Canvas(root, background='green', width=300, height=300)

s1 = canvas.create_rectangle(0, 0, 100, 100, fill='magenta')

s2 = canvas.create_rectangle(100, 0, 200, 100, fill='blue')
s3 = canvas.create_rectangle(200, 0, 300, 100, fill='blue')

canvas.pack()

def change_square(event):
canvas.itemconfigure(s1, fill="blue")

canvas.bind("<Button-1>", change_square)
root.mainloop()

如果您想将中间更改为黑色,您可以使用:

canvas.itemconfigure(s2, fill="black")`

等等。

如果您想根据单击的颜色更改颜色,这应该可行:

 def change_square(event):
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
sq = canvas.find_closest(x,y)[0]
canvas.itemconfigure(sq, fill="black")


canvas.bind("<Button-1>", change_square)
root.mainloop()

关于python - 绑定(bind)/事件给出错误 'int' 对象没有属性 'bind',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29157027/

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