本文介绍了如何获取tkinter画布动态调整窗口宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Python中获取一个画布,将其宽度设置为窗口的宽度,然后当用户使窗口变小/变大时,动态调整画布大小。有没有办法这样做(容易)?提前感谢。

I need to get a canvas in Python to set its width to the width of the window, and then dynamically re-size the canvas when the user makes the window smaller/bigger. Is there any way of doing this (easily)? Thank-you in advance.

推荐答案

我想我会添加一些额外的代码来扩展@ fredtantini的答案,因为它不处理如何更新在 Canvas 上绘制的窗口小部件的形状。

I thought I would add in some extra code to expand on @fredtantini's answer, as it doesn't deal with how to update the shape of widgets drawn on the Canvas.

使用 scale 方法并标记所有窗口小部件。一个完整的例子如下。

To do this you need to use the scale method and tag all of the widgets. A complete example is below.

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

这篇关于如何获取tkinter画布动态调整窗口宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:24