Chris Fowl
Chris Fowl

Reputation: 566

How to center a tkinter widget, ignoring another widget?

I've a three widgets in tkinter with Python 3. One picture (as a label) and two labels. I want the picture to be at the left of a frame, all the way. Then, I want the two labels to be centered across the X-axis, basically ignoring the picture and then centering. The first label needs to go above the second label. How can I achieve this? I've been trying a long time now and I just can't get the ignoring of the picture down.

EDIT: Thanks to DerrickTSE (not sarcastic), I can explain it a little bit better. I did ment the GUI to look like this:

-----------
|         |                             Label 1
|   Pic   |                             -------
|         |                             Label 2
-----------

Where Label 1 & Label 2 are ment to be centered.

Upvotes: 0

Views: 285

Answers (2)

Henry Yik
Henry Yik

Reputation: 22503

Are you looking for something like this? The window can expand and the labels will sit at center.

import tkinter as tk

root = tk.Tk()

pic = """
-----------
|         |
|   Pic   |
|         |
-----------
"""

p = tk.Label(root,text=pic,font="Consolas 8")
p.pack(side="left")

f = tk.Frame(root)

tk.Label(f,text="Label 1").pack()
tk.Label(f,text="-------").pack()
tk.Label(f,text="Label 2").pack()

f.pack(side="left",expand=True)

root.mainloop()

Upvotes: 0

DerrickTSE
DerrickTSE

Reputation: 35

Not sure what exactly you want to organize your UI. So I am assuming you want to achieve something like this:

-----------
|         |  Label 1
|   Pic   |  -------
|         |  Label 2
-----------

Then you can use grid property to organize your widgets. To implement, you can call rowspan in method .grid() to extend specific cell. Thus, brief code should look like this:

pic = tk.Label(frame,...)
pic.grid(column = 0, rowspan = 2) # extend the cell by 2 rows

Label1 = tk.Label(frame,...)
Label1.grid(column = 1, row = 0)

Label2 = tk.Label(frame,...)
Label2.grid(column = 1, row = 1)

For more tkinter grid instruction: Doc

Hope this helps, cheers.

Upvotes: 1

Related Questions