【问题标题】:Tkinter checkbuttons inside of a Text widget and scrolling文本小部件内的 Tkinter 检查按钮和滚动
【发布时间】:2012-02-11 22:27:57
【问题描述】:

使用this stackoverflow post 中的代码,我对其稍作更改,为每个其他检查按钮添加背景颜色,并将宽度设置为填充 Text 小部件的宽度。但是,发生这种情况时,我无法使用鼠标滚轮滚动。我必须抓住滚动条。

有没有更好的方法可以正常滚动?这是我的代码:

import Tkinter as tk

root = tk.Tk()  
vsb = tk.Scrollbar(orient="vertical")
text = tk.Text(root, width=40, height=20, yscrollcommand=vsb.set)
vsb.config(command=text.yview)
vsb.pack(side="right",fill="y")
text.pack(side="top",fill="both",expand=True)
for i in range(1000):
    bg = 'grey'
    if i % 2 == 0:
        bg = 'white'
    cb = tk.Checkbutton(text="checkbutton #%s" % i, bg=bg, width=35, justify=tk.LEFT)
    text.window_create("end", window=cb)
    text.insert("end", "\n") # to force one checkbox per line

root.mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:
    .
    .
    text.focus() # <----------
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      问题在于,当您使用 Checkbuttons 填充 Text 小部件时,您现在会在鼠标悬停在窗口上时与 Checkbuttons 的事件绑定进行交互(而不是“隐藏”的 Text 小部件)。尽管 Text 小部件具有用于鼠标滚动的绑定(按钮 4 和 5),但 Checkbuttons 不会自动附带。并且(AFAIK)父小部件无法自动设置为通过其子小部件接收任何事件,因此您必须手动进行。以下代码将起作用(在 cb 创建后插入):

      cb.bind('<Button-4>', lambda event: text.yview_scroll(-1, tk.UNITS))
      cb.bind('<Button-5>', lambda event: text.yview_scroll( 1, tk.UNITS))
      

      【讨论】:

      • 对我来说cb.bind('&lt;MouseWheel&gt;', lambda event: text.yview_scroll(int(-1*(event.delta/120)), "units")) 有效。谢谢你的主意。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 2019-07-10
      • 2013-05-24
      • 2014-02-13
      • 2012-02-09
      • 2016-08-06
      • 2023-02-10
      相关资源
      最近更新 更多