Python Tkinter Canvas'边框与窗口重叠'create_window'创建

时间:2016-10-22 10:25:20

标签: python canvas tkinter border overlap

我正在使用tkinter制作滚动画布。当我通过create_window链接创建一个窗口时,窗口大于画布,窗口将与画布边框重叠。

import Tkinter as tk


class ScrollCanvas(object):
    """A widget to show table in frame"""
    def __init__(self, parent=None):
        self.parent = parent
        self.frame = tk.Frame(self.parent, bd=3,
                              relief=tk.GROOVE)
        self.frame.pack(fill=tk.BOTH, expand=1)

        self.frame.grid_rowconfigure(0, weight=1)
        self.frame.grid_columnconfigure(0, weight=1)

        self.xscrollbar = tk.Scrollbar(self.frame, orient=tk.HORIZONTAL)
        self.yscrollbar = tk.Scrollbar(self.frame, orient=tk.VERTICAL)
        self.canvas = tk.Canvas(self.frame, bg='#006666',
                                bd=10, relief=tk.GROOVE,
                                xscrollcommand=self.xscrollbar.set,
                                yscrollcommand=self.yscrollbar.set)

        self.xscrollbar.grid(row=1, column=0, sticky=tk.W+tk.E)
        self.yscrollbar.grid(row=0, column=1, sticky=tk.N+tk.S)
        self.canvas.grid(row=0, column=0, sticky=tk.W+tk.E+tk.N+tk.S)

        self.xscrollbar.config(command=self.canvas.xview)
        self.yscrollbar.config(command=self.canvas.yview)

        self.table = tk.Frame(self.canvas, bd=5, relief=tk.SOLID,
                              width=400, height=200)

        self.canvas.create_window(0, 0, anchor=tk.CENTER, window=self.table)
        self.canvas.update_idletasks()
        self.canvas.config(scrollregion=self.canvas.bbox(tk.ALL))


def main():
    app = tk.Tk()
    app.geometry('400x300')
    frame = tk.Frame(app, width=50, height=50)
    frame.propagate(0)
    frame.pack(fill=tk.BOTH, expand=1)
    mytable = ScrollCanvas(parent=frame)
    app.mainloop()

main()

结果是这样的:(红色框)

enter image description here

有谁知道如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

奇怪的是,画布边框是绘图空间的一部分,因此画布上绘制的任何内容都有可能与边框重叠。

我使用的解决方案是从画布中删除边框,然后将画布放在具有边框的框架内。在视觉上它看起来是一样的,但由于可见边框属于另一个小部件,因此画布中的项目不可能与它重叠。

答案 1 :(得分:0)

您可以通过将状态设置为隐藏以及何时需要将其设置为正常状态来解决该问题

import tkinter

...
...

canvas = tkinter.Canvas(self, width=100, height=100, bd=0, highlightthickness=0)
canvas.pack()

btn = tkinter.Button(text="Click me", command=print)

win = canvas.create_window(10, 10, anchor=tkinter.NW, window=btn)

canvas.itemconfigure(win, state=tkinter.HIDDEN)

...
...