简体   繁体   中英

How to dynamically resize window with Tkinter?

root= tk.Tk()
root.title('Quick Googling')
canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()

entry1 = tk.Entry (root) 
canvas1.create_window(200, 140, window=entry1)
canvas1.config(background="#8FB1CC"

button1 = tk.Button(text='Search Google', bg = "blue")
canvas1.create_window(200, 180, window=button1)

I want the colour of my window and the entry and button to utilise all the space when the window's size is changed.

If you use a frame the geometry mangers of tkinter is doing the job for you see:

import tkinter as tk

root= tk.Tk()
root.title('Quick Googling')
myframe = tk.Frame(root)
myframe.pack(fill='both',expand=True)

entry1 = tk.Entry (myframe,background="#8FB1CC")
entry1.pack(fill='x')

button1 = tk.Button(myframe,text='Search Google', bg = "blue")
button1.pack(fill='both',expand=1)
root.mainloop()

Look on a small overview I wrote over the basics.

  1. fill stretch the slave horizontally, vertically or both expand The
  2. slaves should be expanded to consume extra space in their master.

So what the above code does is to create a frame in its natrual size , this means it shrinks itself to the minimum space that it needs to arrange the children.

After this we use for the first time the geometry manager pack and give the options fill , which tells the frame to stretch and using the optional argument expand to consume extra space. Together they resize your frame with the window, since there is nothing else in it.

After that we create an Entry and using once again the method pack to arrange it with this geometry manager. We are using again the optional argument fill and give the value 'x' , which tells the geometry manager to stretch the slave/entry vertically .

So the entry streches vertically if the frame is expandes.

At least we create a Button and using the known keywords, to let it resize with the frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM