创建后如何使用python移动tkinter窗口?



我希望在创建 tkinter 窗口后将其移动到不同的 x 和 y 坐标。例如,创建窗口 5 秒后将其移动到
x=??? 和 y=???.

from tkinter import*
root = Tk()
root.title("lol")
root.geometry("300x300")
photo = PhotoImage(file="pepe.gif")
label = Label(image=photo).place(x=10, y=10)
root.mainloop()

上面的代码只是一个示例,需要如何修改才能自行移动?

此示例将向您展示如何重置控制窗口在屏幕上位置的根几何图形;单击图像将切换窗口的位置。

from tkinter import *
def move_me(idx=[0]):   # <- creates a closure for the index of the location strings
loc = ["300x300+200+200", "300x300+300+300"]

root.geometry(loc[idx[0]])   # <-- reset the geometry
idx[0] = (idx[0]+1) % 2      # <-- toggles the index between 0 and 1
root = Tk()
root.title("lol")
root.geometry("300x300-100+100")
photo = PhotoImage(file="pepe.gif")
button = Button(root, image=photo, command=move_me)
button.place(x=10, y=10)
root.mainloop()

[编辑],自动重复移动窗口。

(注意,你有具有挑战性的游戏来抓住窗户关闭它(

from tkinter import *
import random
def move_me():
x, y = str(random.randrange(800)), str(random.randrange(800))
loc = "300x300+" + x + '+' + y
root.geometry(loc)
root.after(500, move_me)  # <-- auto call to move_me again every 1/2 second
root = Tk()
root.title("lol")
root.geometry("300x300+100+100")
photo = PhotoImage(file="pepe.gif")
label = Label(root, image=photo)
label.place(x=10, y=10)
move_me()      # <-- call to move_me
root.mainloop()

最新更新