如何解决想要使用 Tkinter 通过光标调整形状矩形的大小
我用鼠标成功绘制了矩形,但未能调整其大小。 我已经尝试通过调用函数来使用事件的多种方法,但失败了。
python 新手太挣扎了。
谢谢
解决方法
少数错误 self.current = self.create_rectangle(*self.start,*self.start,width=5)
应该是 self.canvas.create_rectangle(*self.start,width=5)
同样的 self.tag_bind
应该是 self.canvas.tag_bind
从self.canvas.bind("<B1-Motion>",self.on_click)
方法中删除self.__init__(filename)
和openFile
另外,不要忘记导入部分 (from functools import partial
)
您可以对绑定在 self.canvas
上的回调进行调整大小,不需要绑定在矩形项上。
下面是一个简化的例子:
import tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
super().__init__()
self.canvas = tk.Canvas(self,width=512,height=512,cursor="cross")
self.canvas.pack(fill="both",expand=1)
self.canvas.bind("<Button-1>",self.on_button_press)
self.canvas.bind("<B1-Motion>",self.on_move_press)
def on_button_press(self,event):
# find rectangle items under mouse cursor
items = [x for x in self.canvas.find_withtag("current") if self.canvas.type(x) == "rectangle"]
if items:
# item found,use it as the "current" item
self.start = self.canvas.coords(items[0])[:2]
self.current = items[0]
else:
# no item found,create new "current" rectangle item
self.start = event.x,event.y
self.current = self.canvas.create_rectangle(*self.start,width=5)
def on_move_press(self,event):
# resize the "current" item
self.canvas.coords(self.current,event.x,event.y)
ExampleApp().mainloop()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。