我已经有一个 10X10 的正方形网格,我想在单击该网格时在网格中的一个正方形上绘制另一个正方形。
现在,我有在框架中绘制网格的函数和确定正方形坐标(左上角和右下角)的函数。
我遇到问题的部分是
canvas=Canvas()
for row in range(10):
for column in range(10):
canvas.create_rectangle(10+(row*53),10+(column*53),60+(row*53),60+(column*53),fill='blue')
self.bind('<Button-1>',self.changeBlock)
哪里
def changeBlock(self,event):
self.canvas.create_rectangle(upperX(event),upperY(event),lowerX(event),lowerY(event),fill='red')
upperX,upperY,lowerX,lowerY都是确定鼠标所在方 block 坐标的函数。
我不知道为什么当我单击 Canvas 上的某些内容时,changeBlock 不运行。
完整:
class MainFrame(Frame):
def __init__(self,parent):
Frame.__init__(self,parent,background="blue")
self.parent=parent
self.parent.title("simple")
self.parent.geometry("600x600")
self.parent.resizable(0,0)
self.pack(fill=BOTH,expand=1)
canvas=Canvas()
for row in range(10):
for column in range(10):
canvas.create_rectangle(10+(row*53),10+(column*53),60+(row*53),60+(column*53),fill='blue')
self.bind('<Button-1>',self.changeClickBlock)
canvas.pack(fill=BOTH, expand=1)
最佳答案
此代码可以工作,只需对您的代码稍作修改即可。您没有提供相当足够的信息,但足以看出事情......应该正常工作。我正在运行 python3 - 在 python2 中,您可以从“Tkinter”导入。
重要问题:
什么是“self”——你定义了什么类?如果 self 没有派生 某种 tkinter 小部件,然后绑定(bind)到它不会有多大作用。 绑定(bind)会抛出异常吗?
您也没有保存对 Canvas 的引用,所以您怎么知道 后来的 self.canvas 是什么?很令人困惑,但我假设你只是 没有发布完整的代码。
可能的问题:
我的主要猜测是你没有绑定(bind)到 Canvas ,而是在某个地方 别的。确保事件在您想要的小部件上触发。
我的第二个猜测是你忘记打包/网格/放置 Canvas tkinter 顶层。仅仅制作它是不够的,你还需要 以某种方式将其添加到场景中
from tkinter import * root = Tk() canvas=Canvas() # where did you save this? It's very important to keep it! def changeBlock( event=None ): # Here, I'm just making a rectangle of size 10. Make it as big as you want # notice though that you're "self.canvas" will need to reference the # the right thing canvas.create_rectangle(event.x,event.y,event.x+10,event.y+10,fill='red') for row in range(10): for column in range(10): canvas.create_rectangle(10+(row*53),10+(column*53),60+(row*53),60+(column*53),fill='blue') # Here, I'm binding to the Canvas. Bind to the widget where the event occurs canvas.bind('<Button-1>',changeBlock) # make sure you add the widget somehow, or else it won't appear canvas.grid() root.mainloop()
其他建议
Effobt 有一个关于 tkinter 的很棒的教程。这是寻找基本示例的好地方
在 Canvas 项目上: http://effbot.org/tkinterbook/canvas.htm
关于事件: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
关于python - 使用 Tkinter 进行点击绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27351605/