ebug38
ebug38

Reputation: 171

How to place widgets on base of another widget's position?

I want to place my widgets dynamically. If I change the position of one widget all other widgets should be moved aswell.

I tried something like this, but "Test" is not displayed correctly as I want. It is on the left of my entry widget, but I want it + 20px added to TypEntry.

canvas = tk.Canvas(root, height=500, width=300)
canvas.pack()

TypEntry = tk.Entry(root, width=10)
TypEntry.pack()
TypEntry.place(x=xPosForHeader+50, y=yPosForHeader)

ArtikelLabel = tk.Label(root, text="Test")
ArtikelLabel.pack()
ArtikelLabel.place(x=TypEntry.winfo_x()+20, y=yPosForHeader)

Upvotes: 2

Views: 3101

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

It's a little unclear exactly what you're asking, because tkinter provides several ways to place widgets relative to other widgets.

However, if you literally have no constraints other than one widget be placed relative to another, the simplest solution is place. In my experience place is almost never the right solution except in very rare circumstances since you have to do a lot more of the work yourself.

If you read the documentation for place you'll see that there are options specifically for relative placement. These options include relx, rely, relwidth and relheight.

Using your code, it would look like this:

ArtikelLabel.place(in_=TypEntry, relx=1.0, x=20, rely=0)

In this example the options have the following effect:

  • in_ specifies the widget that this widget is relative to

  • relx is a floating point value where 0 means the left edge of the other widget, and 1.0 means the right edge. By using 1.0, we are saying that the want the label to be positioned relative to the far right edge of the entry widget.

  • x is an absolute number. When used in combination with with relx, the values are summed. Thus relx=1.0, x=20 means 20 pixels to the right of the right edge

  • rely specifies that the widget is to be aligned to the top edge of the widget.

Upvotes: 5

Related Questions