文本小部件内的 Tkinter 复选按钮和滚动 [英] Tkinter checkbuttons inside of a Text widget and scrolling

查看:43
本文介绍了文本小部件内的 Tkinter 复选按钮和滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这篇stackoverflow帖子,我稍微改变了它,为每个其他复选按钮添加背景颜色,并设置宽度以填充文本小部件的宽度.但是,当发生这种情况时,我无法使用鼠标滚轮进行滚动.我必须抓住滚动条.

Using the code found in this stackoverflow post, I have altered it slightly to include a background color for every other checkbutton and set the width to fill up the width of the Text widget. However, when this happens, I can not use my mouse wheel to scroll. I have to grab onto the scroll bar.

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

Is there a better way to do this that would allow normal scrolling? Here is my code:

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()

推荐答案

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

The problem is that when you fill up the Text widget with Checkbuttons, you now interact with the Checkbuttons' event bindings when your mouse is over the window (and not the Text widget which is "hidden"). Whereas the Text widget has bindings for mouse scrolling (button 4 and 5), the Checkbuttons don't automatically come with it. And (AFAIK) parent widgets can not be automatically set to receive any events through their children, so you have to do it manually. The following code will work (insert after cb is created):

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

这篇关于文本小部件内的 Tkinter 复选按钮和滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆