Centering and size a windows frame in Tkinter clas

2019-02-19 11:46发布

I want to center a window frame ad set a size using a ratio according to screensize. But I cannot see where to modify my code correctly to perform such program. My program is the following example :

class App:
    def __init__(self,master):
        ScreenSizeX = master.winfo_screenwidth()  # Get screen width [pixels]
        ScreenSizeY = master.winfo_screenheight() # Get screen height [pixels]
        ScreenRatio = 0.8                              # Set the screen ratio for width and height
        FrameSizeX  = int(ScreenSizeX * ScreenRatio)
        FrameSizeY  = int(ScreenSizeY * ScreenRatio)
        FramePosX   = (ScreenSizeX - FrameSizeX)/2 # Find left and up border of window
        FramePosY   = (ScreenSizeY - FrameSizeY)/2

        print FrameSizeX,FrameSizeY,FramePosX,FramePosY

        #geometry(str(self.winfo_screenwidth())+"x"+str(self.winfo_screenheight())+"+0+0")
        frame = Tkinter.Frame(master)
        frame.pack()

        self.button = Tkinter.Button(frame,text="Quit",fg="red",command=frame.quit)
        self.button.pack()

        self.hi_there = Tkinter.Button(frame,text="Hi!",command=self.say_hi)
        self.hi_there.pack()

    def say_hi(self):
        print "hello !"

if __name__ == "__main__":
    root = Tkinter.Tk()
    app = App(root)
    root.mainloop()

2条回答
叛逆
2楼-- · 2019-02-19 12:31

This is the final code working for this feature :

import Tkinter #Python integrated tool kit for interfaces

class App:
    def __init__(self,master):
        # Define frame size and position in the screen :
        ScreenSizeX = master.winfo_screenwidth()  # Get screen width [pixels]
        ScreenSizeY = master.winfo_screenheight() # Get screen height [pixels]
        ScreenRatio = 0.8                              # Set the screen ratio for width and height
        FrameSizeX  = int(ScreenSizeX * ScreenRatio)
        FrameSizeY  = int(ScreenSizeY * ScreenRatio)
        FramePosX   = (ScreenSizeX - FrameSizeX)/2 # Find left and up border of window
        FramePosY   = (ScreenSizeY - FrameSizeY)/2
        master.geometry("%sx%s+%s+%s"%(FrameSizeX,FrameSizeY,FramePosX,FramePosY))
        frame = Tkinter.Frame(master)
        frame.pack()

        self.button = Tkinter.Button(frame,text="Quit",fg="red",command=frame.quit)
        self.button.pack()

        self.hi_there = Tkinter.Button(frame,text="Hi!",command=self.say_hi)
        self.hi_there.pack()

    def say_hi(self):
        print "hello !"

if __name__ == "__main__":
    root = Tkinter.Tk()
    app = App(root)
    root.mainloop()
查看更多
Animai°情兽
3楼-- · 2019-02-19 12:34

Why did you comment out the geometry line? It's quite close to what you need really. Try this:

master.geometry("%sx%s+%s+%s" % (FrameSizeX,FrameSizeY,FramePosX,FramePosY))
查看更多
登录 后发表回答