user1870035
user1870035

Reputation:

Python Tkinter Layout Problems

I'm trying to use .grid() to make a tkinter layout. I have all my buttons aligned on the left side, and I want to put a textbox on the right. The problem is that when I try to do that, it messes up the buttons on the left. I've tried to use multiple frames but it doesn't seem to work. Any ideas?

Upvotes: 0

Views: 1036

Answers (2)

A. Rodas
A. Rodas

Reputation: 20689

If you are using the grid geometry manager, it is not necessary to use Frames for a 2-column layout. You can use rowspan to adjust the height of the Text widget to the number of buttons:

from Tkinter import *

root = Tk()
N = 5

for i in range(N):
    Button(root, text="Button %s" % i).grid(row=i, column=0, padx=5)
Text(root, width=30).grid(row=0, column=1, rowspan=N, padx=5)

root.mainloop()

Upvotes: 1

mgilson
mgilson

Reputation: 310177

one of the most important things to know about the grid geometry manager is the columnspan and rowspan keywords:

import Tkinter as tk

root = tk.Tk()
buttons = [tk.Button(root,text=str(i)) for i in range(6)]
for i,b in enumerate(buttons):
    b.grid(row=i,column=0)

textbox = tk.Text(root)
textbox.grid(row=0,column=1,rowspan=6)

root.mainloop()

Note that a typical usage here is to use a Frame gridded with the correct columnspan and rowspan. Then you can use that to manage the data. An alternative to what I have above would be to use a Frame to hold all of the buttons and then grid the Text widget right next to it:

import Tkinter as tk

root = tk.Tk()
frame = tk.Frame(root)
frame.grid(row=0,column=0)
buttons = [tk.Button(frame,text=str(i)) for i in range(6)]
for i,b in enumerate(buttons):
    b.grid(row=i,column=0)

textbox = tk.Text(root)
textbox.grid(row=0,column=1)

root.mainloop()

Upvotes: 2

Related Questions