【问题标题】:Tkinter how to keep the insert on screen when using mouse wheelTkinter如何在使用鼠标滚轮时将插入保持在屏幕上
【发布时间】:2014-06-16 22:13:14
【问题描述】:

在 Tkinter 中,如何在使用鼠标滚轮滚动 Text 小部件时将文本插入保持在屏幕上(在 Text 小部件中)?

【问题讨论】:

  • 如果你好奇投反对票的原因,他们可能是因为误解(他们认为我的回答是我问题的一部分,他们认为它没有回答一些未知的问题原因,但两种信念都是错误的)。

标签: python event-handling tkinter mouseevent mousewheel


【解决方案1】:

这是代码中问题的示例答案。这不是问题的一部分。这就是答案。我敢肯定有更多的方法来回答它(这就是我写“一个示例”答案的原因)。

from tkinter import *

…

def create_widgets(self):
    …
    self.textWidget.bind("<MouseWheel>", self.mouse_wheel) #Windows mouse wheel
    self.textWidget.bind("<Button-4>", self.mouse_wheel) #Linux mouse wheel
    self.textWidget.bind("<Button-5>", self.mouse_wheel) #Linux mouse wheel (one is for scrolling up and one is for scrolling down, in Linux)

def mouse_wheel(self, event):
    self.textWidget.mark_set(INSERT, "current display linestart") #display makes it uses display lines (as in when word wrap is on in case you have a line that spans a lot of 'display' lines)
    #Don't add return "break" here unless you want to write the entire mouse wheel functionality yourself.

此代码使用mark_set 将插入定位在"current display linestart"(即鼠标指针所在行的开头)。滚动鼠标滚轮时会调用mouse_wheel 方法。这是一个跨平台的解决方案,因为它提供了在 Linux 和其他系统(如 Windows)上执行此操作的方法。

【讨论】:

  • 答案确实回答了这个问题,并且打算回答这个问题的。我问这个问题的唯一原因是用这个答案来回答它(不是因为我需要知道)。答案不是批评。也不是对问题的澄清。它确实有效并且是经过测试的代码。
  • 我编辑了答案,以更清楚地表明代码是答案,而不是问题的一部分,并在之后解释了它如何回答问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2014-07-28
  • 2019-01-22
相关资源
最近更新 更多