简体   繁体   English

如何使用after更改tkinter中的窗口几何形状?

[英]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. 例如,它应该向下显示100个像素,并在左上角向左显示100个像素。 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. EDIT1:我将root.geometry("+{}+{}".format(x + 100, y + 100))放入函数中,但没有帮助。 Also I added print statement to see how this function works and it's called only once at the beginning. 我还添加了print语句,以查看此函数的工作方式,并且在开始时仅调用一次。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM