Skip to main content
 首页 » 编程设计

python之TkInter:利用错误的位置

2025年05月04日10kuangbin

我在 Canvas 上加载图片。这是一张大图片,所以我需要垂直和水平滚动才能看到它。我还让用户使用鼠标指针在图像上绘制随机曲线/线。

一切正常,除了当我水平或垂直滚动​​然后尝试绘制时,我发现曲线没有绘制在鼠标指向的位置,而是绘制在其他位置。我该如何解决这个问题?

这是我的代码:

import PIL.Image 
import PIL.ImageTk 
from Tkinter import *     
import numpy as np 
import cv2    
 
class ExampleApp(Frame): 
   def __init__(self,master): 
        Frame.__init__(self,master=None) 
        self.x = self.y = 0 
        self.imcv=None 
        self.canvas=Canvas(self,width=600,height=600) 
        self.b1="up" 
        self.liste=[] 
        self.xold=None 
        self.yold=None 
 
   def dessiner(self): 
       # Load the imge and allow user to scroll it if it is large. 
       self.canvas.bind("<Motion>",self.motion) 
       self.canvas.bind("<ButtonPress-1>",self.b1down) 
       self.canvas.bind("<ButtonRelease-1>",self.b1up) 
       self.sbarv=Scrollbar(self,orient=VERTICAL) 
       self.sbarh=Scrollbar(self,orient=HORIZONTAL) 
       self.sbarv.config(command=self.canvas.yview) 
       self.sbarh.config(command=self.canvas.xview) 
 
       self.canvas.config(yscrollcommand=self.sbarv.set) 
       self.canvas.config(xscrollcommand=self.sbarh.set) 
 
       self.canvas.grid(row=0,column=0,sticky=N+S+E+W) 
       self.sbarv.grid(row=0,column=1,stick=N+S) 
       self.sbarh.grid(row=1,column=0,sticky=E+W) 
       self.im = PIL.Image.open("image.jpg") 
       self.widt,self.heigt=self.im.size 
       self.canvas.config(scrollregion=(0,0,self.widt,self.heigt)) 
       self.tk_im = PIL.ImageTk.PhotoImage(self.im) 
       self.canvas.create_image(0,0,anchor="nw",image=self.tk_im)    
 
 
   def b1up(self,event): 
       self.b1="up" 
   def b1down(self,event): 
       self.b1="down" 
       self.xold=None 
       self.yold=None 
       self.liste.append((self.xold,self.yold)) 
   def motion(self,event): 
       if self.b1=="down": 
           if self.xold is not None and self.yold is not None: 
               event.widget.create_line(self.xold,self.yold,event.x,event.y,fill="red",width=3,smooth=TRUE) 
           self.xold=event.x 
           self.yold=event.y 
           self.liste.append((self.xold,self.yold)) 
 
 
if __name__ == "__main__": 
    root=Tk() 
    app = ExampleApp(root) 
    app.pack() 
    app.dessiner() 
    root.mainloop() 

如果你想看我的问题可以下载this大图像并将其命名为 image.jpg 并运行代码。

可能解决方案在于使用 canvasx和 canvasy但我不知道怎么办。

提前致谢

请您参考如下方法:

事件对象中的坐标在窗口坐标系中。您需要将它们转换为 Canvas 坐标系。 Tkinter 有两种方法:canvasx和 canvasy .