Funciones para hacer ventanas 'pegadas' en tkinter

Nov 11 2020

Usando tkinter quiero implementar una característica divertida en mi programa. Al hacer clic en el botón que representa la fecha del mes en mi calendar.window, se muestra una nueva ventana donde cualquiera puede tomar notas y esta ventana debe "pegarse" en calendar.window. Intentar extraer si la primera o la última ventana debe resultar en arrastrar ambas . Ejemplo de arrastre incorrecto. Si no existe esa función, tal vez haya medios para hacer que las ventanas aparezcan en una posición predefinida y deshabilitar la función de arrastre.

Main_module

import tkinter as tk
import re
from Calendar import show_calendar
from Notes_widget import show_notes_widget

class MainMenu(tk.Frame):
    def __init__(self, parent,):
        super().__init__(parent)
        self.init_main()

        # Configuring Frame object on the Main window
    def init_main(self):
        self.btn1 = tk.Button(text='Choose the date', width=20, height=3, command=show_calendar)
        self.btn2 = tk.Button(text='Enter your notes', width=20, height=3,
                              command=lambda : show_notes_widget(self.get_root_position()))

        self.btn1.pack()
        self.btn2.pack()

    def get_root_position(self):
        self.update_idletasks()
        self.width, self.height, self.x, self.y = re.split(r'[x+]', root.geometry())
        return self.width, self.height, self.x, self.y

if __name__ == '__main__':
    # Creating Main window
    root = tk.Tk()
    root.title('ИВРО')
    root.update_idletasks()
    root.width = 180
    root.height = 110
    root.x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
    root.y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
    root.geometry(f'{root.width}x{root.height}+{int(root.x - root.width / 2)}+{int(root.y - root.height / 2)}')
    root.resizable(False, False)

    # Creating Frame object
    app = MainMenu(root)
    app.pack()

    root.mainloop()

y el segundo módulo

import tkinter as tk

class NotesWidget(tk.Toplevel):
    def __init__(self, *args):
        tk.Toplevel.__init__(self)

        self.width, self.height, self.x, self.y = args
        self.init_child()

    def init_child(self):
        self.title("Введите заметку")

        self.text = tk.Text(self, height = 26, width = 35, bg="darkgreen", fg='white',
                            wrap='word', font=('Verdana', 10, 'bold'))
        self.text.pack()
        self.text.grid_propagate(True)
        self.btn = tk.Button(self, text='Добавить')
        self.btn.pack(ipady=10)


        self.geometry(f'300x465+{int(self.x) + int(self.width) + 12}+{int(self.y) - int(self.height)}')
        self.resizable(False, False)
        self.grab_set()
        self.focus_set()


def show_notes_widget(coordinates):
    width, height, x, y = coordinates
    notes_widget=NotesWidget(width, height, x, y)
    notes_widget.mainloop()

Respuestas

BryanOakley Nov 12 2020 at 00:38

La función que solicita se denomina comúnmente "acoplada" en lugar de "pegada".

Si bien tkinter no lo admite directamente, es bastante fácil de simular. Tkinter proporciona métodos para mover una ventana y una forma de saber cuándo se mueve una ventana. Todo lo que necesita hacer es detectar cuándo se mueve la ventana principal y mover la otra ventana para que coincida con la nueva ubicación.

El evento <Configure>se activará cada vez que se mueva una ventana (y por algunas otras razones). Agregar un enlace a ese evento funciona bien para mantener la ventana acoplada en la ubicación correcta.

He aquí un ejemplo sencillo. El segundo se retrasará cuando se mueva la ventana principal, pero creo que eso es inevitable.

import tkinter as tk
import re

root = tk.Tk()
other = tk.Toplevel(root)

def dock(child, master):
    width, height, x, y = re.split(r'[x+]', master.geometry())
    x = int(x) + master.winfo_width()
    child.geometry(f"+{x}+{y}")

root.bind("<Configure>", lambda event: dock(other, root))
root.mainloop()