如何在tkinter画布中居框架

时间:2014-12-29 16:59:06

标签: python canvas tkinter frame

我有几个Windows的GUI。其中一个Windows太大了,所以不得不实现一个Scrollbar,它必须用Canvas完成。这导致了一个问题,即Canvas永远不会位于Window的中间,它自动具有显示的大小。

如何将画布置于显示窗口的中间(和顶部)并将滚动条保持在右侧? 我知道第一帧(frame0)并不是真的需要,但它让我以后更容易。 我更新了下面的脚本,因此它可以作为独立运行。我知道这不是很好,但它是我所有代码的总结。

感谢您的帮助。

from Tkinter import *


class GUI:

    def __init__(self, parent):

        self.myParent = parent

        self.frame = Frame(self.myParent, bd = 2, relief = GROOVE, padx = 20, pady = 20)


        self.RWidth=self.frame.winfo_screenwidth()
        self.RHeight=self.frame.winfo_screenheight()
        self.myParent.geometry("%dx%d+0+0" % (self.RWidth, self.RHeight))  # Make Window fullscreen if no other geometry definition


    def GUI(self):

        self.myParent.title("Transport to Sorting-Point")  # Title of Window

        self.frame0 = Frame(self.myParent)
        self.frame0.pack(expand=True, fill=BOTH)     
        self.canvas = Canvas(self.frame0)
        self.vsb = Scrollbar(self.frame0, orient=VERTICAL, command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set, highlightthickness=0)
        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side=TOP, anchor=W, expand=True, fill=BOTH)
        self.frame = Frame(self.canvas, bd = 2, relief = GROOVE, padx = 20, pady = 20)
        self.canvas.create_window((0,0), window=self.frame, anchor = N)
        self.frame.bind("<Configure>", self.OnFrameConfigure)

        self.Text = Label(self.frame, text='This is a Text ', justify = LEFT).grid(row=0, column=0)


        self.frame0.mainloop()

    def OnFrameConfigure(self, event):
        self.canvas.config(scrollregion = self.canvas.bbox('all'))


def main():         
    root = Tk()
    myapp = GUI(root)
    myapp.GUI()

    root.option_clear

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

既然您知道画布的宽度和高度,只需将框架放在画布的中心,只需要一点点数学:

x0 = self.frame.winfo_screenwidth()/2
y0 = self.frame.winfo_screenheight()/2
self.canvas.create_window((x0,y0), window=self.frame, anchor = "center")