Jakub Bielan
Jakub Bielan

Reputation: 605

How to change window geometry in tkinter using after?

What I want to achieve is displaying an image on another application window with regard to its coordinates. For example, it should appear 100 pixels down and 100 pixels left to the left upper corner. I am using transparent window for the image, and it displays an image properly but it doesn't update its coordinates.

Here is my code:

import tkinter as tk # Python 3
from functions import window_coordinates   # it takes x, y, width, heigth of the window


x, y, w, h = window_coordinates("window_name")

def update_coordinates():
    global x, y, w, h
    x, y, w, h = window_coordinates("window_name")
    root.geometry("+{}+{}".format(x + 100, y + 100))
    print("update_coordinates function")

root = tk.Tk()
# The image must be stored to Tk or it will be garbage collected.
root.image = tk.PhotoImage(file='path/to/image.png')
label = tk.Label(root, image=root.image, bg='white')
root.overrideredirect(True)
root.geometry("+{}+{}".format(x+100, y+100))
root.lift()
root.wm_attributes("-topmost", True)
root.wm_attributes("-disabled", True)
root.wm_attributes("-transparentcolor", "white")
label.pack()

label.after(100, update_coordinates)
label.mainloop()

Thanks for help.

EDIT1: I put root.geometry("+{}+{}".format(x + 100, y + 100)) inside the function but it didn't help. Also I added print statement to see how this function works and it's called only once at the beginning.

Upvotes: 1

Views: 2779

Answers (1)

Jakub Bielan
Jakub Bielan

Reputation: 605

OK, I found the answer. There was a mistake in the function. Callback didn't work. Right code:

import tkinter as tk # Python 3
from functions import window_coordinates


x, y, w, h = window_coordinates("3949206036")

def update_coordinates():
    global x, y, w, h
    x, y, w, h = window_coordinates("3949206036")
    root.geometry("+{}+{}".format(x + 100, y + 100))
    label.after(1, update_coordinates)           #  This addition was needed

root = tk.Tk()
# The image must be stored to Tk or it will be garbage collected.
root.image = tk.PhotoImage(file='d:/Python/Projects/Data-mining/samples/avatar.png')
label = tk.Label(root, image=root.image, bg='white')
root.overrideredirect(True)
root.geometry("+{}+{}".format(x+100, y+100))
root.lift()
root.wm_attributes("-topmost", True)
root.wm_attributes("-disabled", True)
root.wm_attributes("-transparentcolor", "white")
label.pack()

label.after(1, update_coordinates)
label.mainloop()

Upvotes: 1

Related Questions