Kitch
Kitch

Reputation: 31

How to change the window size after the program starts?

I want that after starting the program, it checks its actual size and when "window.winfo_width > 520" it changes its size to 520. Is it possible?

from tkinter import *
from time import *

def upd():
    tstr = strftime("%I:%M:%S %p")
    ltime.config(text=tstr)

    lday.config(text=strftime("%A"))

    dtstr = strftime("%B %d, %Y")
    ldate.config(text=dtstr)
    ltime.after(1000, upd)


window = Tk()
window.config(bg='black')
window.title("Clock")
window.geometry('520x300')
window.resizable(0,1)


ltime = Label(window, font="Adobe 60", text='', fg='green', bg='black')
ltime.pack()
lday = Label(window, font="Adobe 60", text='', fg='green', bg='black')
lday.pack()
ldate = Label(window, font="Adobe 60", text='', fg='green', bg='black')
ldate.pack()

upd()

window.mainloop()

Upvotes: 3

Views: 16574

Answers (1)

Kartikeya
Kartikeya

Reputation: 838

Firstly, window.winfo_geometry() will give you the geometry of the window.

For getting width only, use window.winfo_width().

For getting height only, use window.winfo_height()

e.g.

if window.winfo_width() > 520 :
     window.geometry('520x300')

Now, since you are using window.resizable(0,1), you are disabling the window's width to be resized, so windows's width will be fixed to 520. So, how will it exceed 520, if it's not resizable? If you enable it, and then want window's width to not exceed 520:

Tkinter offers .maxsize() and .minsize() to fix the size of the root window.

e.g. if you want that the window's width to not exceed 520, then just set the width in maxsize as 520.

window.geometry('520x300')
window.maxsize(520, 300)

The window's width will not be resized more than 520 now.


In case, you want to resize according to the user's screen's size:

To get the screen size, you can use winfo_screenwidth() which returns the screen width and winfo_screenheight() for the height of the screen in pixels.

window.geometry() can be recalled if needed.


EDIT: An example of recalling window.geometry() after the start of program(, even after resizing is disabled horizontally):

def resizeScreen():
    window.geometry('520x300')

b = Button(window, text="RESIZE", command=resizeScreen)
b.pack()

Whenever this button is clicked, the screen will be resized, from what it is currently. You can call this same function without using a button, by just calling the function. It depends on your code, how you use it.

Upvotes: 2

Related Questions