【发布时间】:2022-10-15 01:47:00
【问题描述】:
我面临的问题很简单:
我有一个带有root.overrideredirect(True) 的tkinter 窗口,因此,我必须使用相应的绑定制作自己的move_window(event)。它确实有效,但是当我用鼠标拖动它时,窗口会重新定位,使得窗口的左上角位于我的鼠标位置。
我想要的是:
像我们使用日常应用程序一样平滑拖动。
带有绑定的窗口和移动功能的代码:
from tkinter import *
import pyautogui as pg
bg_color= '#ededed'
root = Tk()
close = PhotoImage(file='assets/close_button.png')
close_active = PhotoImage(file='assets/close_button_active.png')
root.overrideredirect(True)
root.title("Google Drive")
root.geometry("1000x600")
root.update()
# Creating a canvas for placing the squircle shape.
canvas = Canvas(root, height=root.winfo_height(), width=root.winfo_width(), highlightthickness=0)
canvas.pack(fill='both')
canvas.update()
# make a frame for the title bar
title_bar = Frame(canvas, bg=bg_color, relief='raised', bd=0)
title_bar.pack(expand=1,fill='x')
title_bar.update()
# put a close button on the title bar
close_button = Button(title_bar, image=close, command= root.destroy,padx = 2,pady = 2,bd = 0,font="bold",highlightthickness=0)
close_button.pack(side='right')
close_button.update()
# a canvas for the main area of the window
window = Canvas(canvas, bg=bg_color,highlightthickness=0)
window.pack(expand=1,fill='both')
window.update()
# Placing the window in the center of the screen
def place_center():
global x, y
reso = pg.size()
rx = reso[0]
ry = reso[1]
x = int((rx/2) - (root.winfo_width()/2))
y = int((ry/2) - (root.winfo_height()/2))
root.geometry(f"+{x}+{y}")
# Bind Functions
def move_window(event):
root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))
def change_on_hovering(event):
global close_button
close_button['image']=close_active
def return_to_normalstate(event):
global close_button
close_button['image']=close
xwin=None
ywin=None
# Bindings
title_bar.bind('<B1-Motion>', move_window)
close_button.bind('<Enter>',change_on_hovering)
close_button.bind('<Leave>',return_to_normalstate)
# Function Calls
place_center()
root.mainloop()
这是我尝试过的另一个移动功能,但窗口有点小故障
def move_window(event):
relx = pg.position().x - root.winfo_x()
rely = pg.position().y - root.winfo_y()
root.geometry('+{0}+{1}'.format(relx, rely))
有任何想法吗?我怀疑这是一个简单的数学计算
【问题讨论】:
-
关键是,当您收到“按下按钮”事件时,您需要注意鼠标相对于窗口左上角的位置。什么时候,当鼠标移动时,你可以根据它来调整你的位置。你原来的单行函数几乎是正确的,你只需要补偿点击位置。