简体   繁体   中英

Python tkinter Grid Manager doesn't place button on left with sticky = tk.W or sticky = 'w'

With two frames within a frame, button placed in top frame, sticky=tk.W doesn't seem to have any effect.

import tkinter as tk
def _exit():
    raise SystemExit

root = tk.Tk()
frame = tk.Frame(root,width = 1200, height = 650, bg = 'Yellow')
top_frame = tk.Frame(frame, width = 1200, height = 50, bg = 'green')
bot_frame = tk.Frame(frame, width = 600, height = 600, bg = 'skyblue') 
exit_button = tk.Button(top_frame, text = 'Exit',
                    command = _exit)
frame.grid()
top_frame.grid(column=0,row=0)
bot_frame.grid(column=0,row=1)
exit_button.grid(column=0,row=0, sticky = tk.W)
                      
root.mainloop()

If I delete the bottom frame, the sticky works:

import tkinter as tk
def _exit():
    raise SystemExit

root = tk.Tk()
frame = tk.Frame(root,width = 1200, height = 650, bg = 'Yellow')
top_frame = tk.Frame(frame, width = 1200, height = 50, bg = 'green')
exit_button = tk.Button(top_frame, text = 'Exit',
                command = _exit)
frame.grid()
top_frame.grid(column=0,row=0)
exit_button.grid(column=0,row=0, sticky = tk.W)

root.mainloop()

When you place a button inside of top_frame , it will shrink to fit the button. The button is to the left of top_frame , but top_frame is only as wide as the button and is centered in its space. Therefore it appears that the button isn't on the left, but it is. The button is on the left edge of top_frame , but top_frame is centered in frame .

If you want top_frame to fill the width of the window (or the width of the space allocated to it) you need to use sticky with it, too.

top_frame.grid(column=0,row=0, sticky="ew")

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