¿Cómo hacer que tkinter canvas cambie dinámicamente el tamaño al ancho de la ventana?


Necesito obtener un lienzo en tkinter para establecer su ancho al ancho de la ventana, y luego cambiar dinámicamente el tamaño del lienzo cuando el usuario hace que la ventana sea más pequeña/más grande.

¿hay alguna manera de hacer esto (fácilmente)?

Author: nbro, 2014-04-03

2 answers

Pensé en añadir un código extra para ampliar La respuesta de@fredtantini, ya que no trata sobre cómo actualizar la forma de los widgets dibujados en el Canvas.

Para hacer esto necesitas usar el método scale y etiquetar todos los widgets. Un ejemplo completo está abajo.

from Tkinter import *

# a subclass of Canvas for dealing with resizing of windows
class ResizingCanvas(Canvas):
    def __init__(self,parent,**kwargs):
        Canvas.__init__(self,parent,**kwargs)
        self.bind("<Configure>", self.on_resize)
        self.height = self.winfo_reqheight()
        self.width = self.winfo_reqwidth()

    def on_resize(self,event):
        # determine the ratio of old width/height to new width/height
        wscale = float(event.width)/self.width
        hscale = float(event.height)/self.height
        self.width = event.width
        self.height = event.height
        # resize the canvas 
        self.config(width=self.width, height=self.height)
        # rescale all the objects tagged with the "all" tag
        self.scale("all",0,0,wscale,hscale)

def main():
    root = Tk()
    myframe = Frame(root)
    myframe.pack(fill=BOTH, expand=YES)
    mycanvas = ResizingCanvas(myframe,width=850, height=400, bg="red", highlightthickness=0)
    mycanvas.pack(fill=BOTH, expand=YES)

    # add some widgets to the canvas
    mycanvas.create_line(0, 0, 200, 100)
    mycanvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))
    mycanvas.create_rectangle(50, 25, 150, 75, fill="blue")

    # tag all of the drawn widgets
    mycanvas.addtag_all("all")
    root.mainloop()

if __name__ == "__main__":
    main()
 26
Author: ebarr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-09 21:28:35

Puede usar el gestor de geometría .pack:

self.c=Canvas(…)
self.c.pack(fill="both", expand=True)

Debería hacer el truco. Si el lienzo está dentro de un marco, haga lo mismo con el marco:

self.r = root
self.f = Frame(self.r)
self.f.pack(fill="both", expand=True)
self.c = Canvas(…)
self.c.pack(fill="both", expand=True)

Ver effbot para más información.

Editar: si no desea un lienzo "de tamaño completo", puede vincular su lienzo a una función:

self.c.bind('<Configure>', self.resize)

def resize(self, event):
    w,h = event.width-100, event.height-100
    self.c.config(width=w, height=h)

Ver effbot de nuevo para eventos y enlaces

 8
Author: fredtantini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-24 11:09:15