Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

python - Tkinter.grid spacing options?

I'm new to Tkinter, and I tried creating an app with the grid layout manager. However, I can't seem to find a way to utilize it the way I want to. What I need to do is simulate a grid full of 'cells' so that I can place, for example, a label in cell (3,8) or a button in cell (5,1). Here is an example of what I've tried:

import tkinter as tk
root = tk.Tk()

label = tk.Label(root, text = 'Label')
label.grid(column = 3, row = 8)

button = tk.Button(root, text = 'Button')
button.grid(column = 5, row = 1)

Tkinter keeps the relative position of each widget (i.e. button is above and to the right of label), but it ignores any space in between. I've searched a bit for this problem and found out about weight, but that doesn't seem to be what I'm looking for; I'd like something independent of the label and button's layouts. Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can specify the spacing on columns/rows in the grid (including those that contain no widget) by running the grid_columnconfigure and grid_rowconfigure methods on the parent of the widgets (in this case, the parent would be root).

For example, to set a minimum width for the 4th column, add the last line to your code:

import Tkinter as tk
root = tk.Tk()

label = tk.Label(root, text = 'Label')
label.grid(column = 3, row = 8)

button = tk.Button(root, text = 'Button')
button.grid(column = 5, row = 1)

root.grid_columnconfigure(4, minsize=100)  # Here

If you want to set a minimum size for all of your columns and rows, you can iterate through them all using:

col_count, row_count = root.grid_size()

for col in xrange(col_count):
    root.grid_columnconfigure(col, minsize=20)

for row in xrange(row_count):
    root.grid_rowconfigure(row, minsize=20)

Edit Interestingly, effbot states:

minsize=Defines the minimum size for the row. Note that if a row is completely empty, it will not be displayed, even if this option is set.

(italics mine) but it seems to work even for rows and columns that are empty, as far as I've tried.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...