简体   繁体   English

如何在tkinter中扩展画布内部的框架?

[英]How to expand a frame inside a canvas in tkinter?

I created a canvas and then a frame as a child of the canvas. 我创建了一个画布,然后创建了一个框架作为画布的子级。 I found, the I should not use pack() to put the frame in the canvas. 我发现,我不应该使用pack()将框架放在画布中。 I used 我用了

my_canvas.create_window(0,0,window=my_frame, anchor='nw')

But I would like my frame be resizable with my app. 但我希望我的应用程序可以调整框架大小。 Thus, I think, I need to put something like fill=BOTH, expand=YES for my frame. 因此,我认为我需要为框架添加诸如fill=BOTH, expand=YES的内容。

You can set the height and width of the canvas window to match the width and height of the canvas. 您可以设置画布窗口的高度和宽度以匹配画布的宽度和高度。 You want to do this every time the canvas changes shape, which can be done by using a bind on the <Configure> event: 您希望每次画布更改形状时都执行此操作,这可以通过在<Configure>事件上使用绑定来完成:

import tkinter as tk

def onCanvasConfigure(e):
    canvas.itemconfig('frame', height=canvas.winfo_height(), width=canvas.winfo_width())

root=tk.Tk()

canvas = tk.Canvas(root, background="blue")
frame = tk.Frame(canvas, background="red")

canvas.pack(expand=True, fill="both")
canvas.create_window((0,0), window=frame, anchor="nw", tags="frame")

canvas.bind("<Configure>", onCanvasConfigure)

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM