如何防止在 tkinter 中选择画布?

问题描述 投票:0回答:1

我目前正在使用 tkinter 开发一个应用程序,并且正在努力解决外观问题。将条目添加到画布时,tkinter 会在条目和画布周围显示选择光标。我想避免画布的这种行为,因为我使用它来创建一个可滚动框架,这会产生非常不愉快的效果,选择仅显示在侧面,因为画布的其余部分位于屏幕之外。

我创建了一个小代码示例来对此进行实验。

这里是没有选择的显示: 不选择

这是包含选择的显示: 选择

我想避免画布周围出现深灰色矩形,你知道该怎么做吗?

这是我的代码示例:

###########
# Imports #
###########

import tkinter as tk
from tkinter import ttk

#########
# Class #
#########

class ScrollableFrame(ttk.Frame):
    def __init__(self, container, *args, **kwargs):
        super().__init__(container, *args, **kwargs)
        canvas = tk.Canvas(self, takefocus=0)
        self.canvas = canvas
        scrollbar = ttk.Scrollbar(self, orient="vertical", command=canvas.yview)
        self.scrollable_frame = ttk.Frame(canvas, takefocus=0)
        self.scrollable_frame.columnconfigure(index=0, weight=1)

        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(
                scrollregion=canvas.bbox("all")
            )
        )

        self.scrollable_frame_id = canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")

        canvas.configure(yscrollcommand=scrollbar.set)
        self.canvas.bind('<Configure>', self.on_width_change)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
    def on_mousewheel(self, event):
        shift = (event.state & 0x1) != 0
        scroll = -1 if event.delta > 0 else 1
        if shift:
            self.canvas.xview_scroll(scroll, "units")
        else:
            self.canvas.yview_scroll(scroll, "units")

    def on_width_change(self, event):
        canvas_width = event.width
        self.canvas.itemconfig(self.scrollable_frame_id, width=canvas_width * 0.99)

    def bind_tree(self, event, callback, widget=None):
        """
        Binds an event to a widget and all its descendants.
        """

        if widget is None:
            widget = self

        if isinstance(widget, ttk.Combobox):
            return

        widget.bind(event, callback, "")

        for child in widget.children.values():
            self.bind_tree(widget=child, event=event, callback=callback)

    def bind_list(self, widgets, event, callback):
        for widget in widgets:
            self.bind_tree(widget=widget, event=event, callback=callback)

    def set_mouse_scroll_on_list(self, widgets):
        self.bind_list(widgets, "<MouseWheel>", self.on_mousewheel)


###########
# Process #
###########

root = tk.Tk()

frame = ScrollableFrame(root)
frame.grid(row=0,column=0,sticky="nsew")

entry = ttk.Entry(frame.scrollable_frame)
entry.pack()

root.mainloop()
python tkinter tkinter-canvas
1个回答
0
投票

这是由于

highlightthickness
没有设置为零造成的。将其设置为零即可修复它:

canvas = tk.Canvas(self, takefocus=0, highlightthickness=0)
© www.soinside.com 2019 - 2024. All rights reserved.