- 1 year ago
Move two windows together tkinter
To move two windows together in Tkinter, you can use the geometry
method of the Tk
or Toplevel
widgets to set the position of the windows. Here's an example that demonstrates how to move two windows together:
pythonimport tkinter as tk
def move_windows():
# Get the position of the first window
window1_position = f"{window1.winfo_x()}x{window1.winfo_y()}"
# Set the position of the second window to match the first window
window2.geometry(window1_position)
# Create the first window
window1 = tk.Tk()
window1.geometry("200x200")
window1.title("Window 1")
# Create the second window
window2 = tk.Toplevel(window1)
window2.geometry("200x200")
window2.title("Window 2")
# Create a button to move the windows together
move_button = tk.Button(window1, text="Move Windows", command=move_windows)
move_button.pack()
# Start the Tkinter event loop
window1.mainloop()
In this example, we create two windows (window1
and window2
) using Tk
and Toplevel
classes. We define a function move_windows
that retrieves the position of the first window using winfo_x()
and winfo_y()
methods. Then, we set the geometry of the second window (window2
) using the retrieved position. Finally, we create a button that triggers the move_windows
function when clicked.
When you run the script, you can move the first window manually by dragging it, and when you click the "Move Windows" button, the second window will be positioned to match the first window's location.
Note: The geometry
method accepts a string argument in the format "widthxheight+x+y" where width
and height
are the dimensions of the window, and x
and y
are the coordinates of the top-left corner of the window.