user2828408
user2828408

Reputation: 65

How to center frame in tkinter Canvas

I have a GUI with several Windows. One of the Windows is too big, so had to implement a Scrollbar, which had to be done with a Canvas. This caused, the problem, that the Canvas is never center in the middle of the Window, which automatically has the size of the display.

How Can I center the Canvas in the middle (and top) of the display-Window and still keep the Scrollbar to the right? I know that the first frame (frame0) is not really needed, but it makes it easier for me afterwards. I updated the script below, so it is able to run as standalone. I know it is not really nice, but it is a pritty much a summary of all my code.

Thanks for your help.

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

Upvotes: 1

Views: 7922

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386362

Since you know the width and height of the canvas, simply place the frame in the center of the canvas with a little math:

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

Upvotes: 2

Related Questions