Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to swap two widgets' x position in tkinter?

I need to create a function that takes as a parameter two widgets and the frame they are placed. I want to swap their X position, but I can't figure out the correct way of doing it. This is what I tried:

def swap(w1, w2, frame):
    x1 = w1.winfo_x()
    x2 = w2.winfo_x()
    w1.place(x=x2)
    w2.place(x=x1)
    frame.update()

What's the right way of doing this? Is this the right approach?


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

1 Answer

0 votes
by (71.8m points)

You can change the position using place_configure.

Here is an example to swap two labels:

from tkinter import *

def swap():
    root.update()
    x1 = label.winfo_x()
    x2 = label2.winfo_x()

    label.place_configure(x=x2)
    label2.place_configure(x=x1)
    
root = Tk()

label = Label(root, text='Hello')
label.place(x=100, y=100)

label2 = Label(root, text='Hello2')
label2.place(x=150, y=100)

btn = Button(root, text='Swap', command=swap)
btn.place(x=125, y=150)

root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...