Python Tkinter在滚动屏幕上修复文本位置

时间:2017-03-27 18:37:52

标签: python-3.x tkinter

尝试在屏幕上滚动图形,同时将文本保持在同一位置。文本显示鼠标的位置。我已经想过在屏幕滚动的相反方向滚动文本的想法,但我不确定是否有更简单的方法,如果我必须以相反的方式滚动文本我不确定如何设置初始文本指针,以便我可以返回并重新调用/重置它。我只是希望它能够在不久的将来表现出不会做其他事情的立场。

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.keys = dict.fromkeys(('Left', 'Right', 'Up', 'Down'))

        self.canvas = tk.Canvas(self, background="bisque", width=700, height=700)
        self.canvas.pack(fill="both", expand=True)
        self.canvas.configure(scrollregion=(-1000, -1000, 1000, 1000))

        self.looper() # start the looping

    def keypress(self,event):
        if event.keysym in self.keys:
        # event type 2 is key down, type 3 is key up
            self.keys[event.keysym] = event.type == '2'

    def looper(self):
        if self.keys['Up']:
            self.canvas.yview_scroll(-2,'units')
        if self.keys['Down']:
            self.canvas.yview_scroll(2,'units')
        if self.keys['Left']:
            self.canvas.xview_scroll(-2,'units')
        if self.keys['Right']:
            self.canvas.xview_scroll(2,'units')

        self.after(5, self.looper) # set the refresh rate here ... ie 20 milliseconds. Smaller number means faster scrolling

    def on_press(self, event):
        self.last_x = event.x
        self.last_y = event.y
        self.startx, self.starty = self.canvas.canvasx(event.x),self.canvas.canvasy(event.y)

    def on_motion(self, event):
        self.canvas.delete("sx")
        self.startx, self.starty = self.canvas.canvasx(event.x),self.canvas.canvasy(event.y)
        px = round(-(((1000-self.startx) * .00015) + 69.3),5)
        py = round((45.05-((1000+self.starty) * .00015)),5)
        self.canvas.create_text(400,-400, text = str(px), fill = "black", tags = "sx")
        self.canvas.create_text(475,-400, text = str(py), fill = "black", tags = "sx")

    def button_motion(self,event):
        delta_x = event.x - self.last_x
        delta_y = event.y - self.last_y
        self.last_x = event.x
        self.last_y = event.y

        self.canvas.xview_scroll(-delta_x, "units")
        self.canvas.yview_scroll(-delta_y, "units")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是使用未嵌入到画布中的窗口小部件,以便在画布滚动时不会滚动。创建一个Label,其父级为画布,然后使用place将标签叠加在画布顶部。