首页 > 解决方案 > 是否可以将 create_window() 框架拉伸到父(或根)的大小?

问题描述

我想让我的聊天室应用程序 gui 可调整大小。

我有一个canvas和它上面的msg_frame所有消息将被放入的地方。

画布设置在根上,place()因此它保持相对于根窗口大小。我也想msg_frame调整相对于画布(或根)的大小。

所以当我调整根窗口的大小时,消息不会像这样显示(蓝色是 msg_frame): 在此处输入图像描述

但坚持右侧(靠近滚动条)。

这是我的代码(为了便于阅读,删除了样式):

root = tk.Tk()
root.title("Chatroom")
root.geometry("1200x800")

chat_canvas = tk.Canvas(root, height=580, width=1160)
msg_frame = tk.Frame(chat_canvas, bg="blue", height=550, width=1160)

# scrollbar
canvas_sb = tk.Scrollbar(top_frame, orient='vertical', command=chat_canvas.yview)
chat_canvas.configure(yscrollcommand=canvas_sb.set)

# placing the scrollbar and canvas
chat_canvas.place(relwidth=0.98, relheight=1)
canvas_sb.place(relx=0.985, relheight=1)

create msg_frame window on canvas
chat_canvas.create_window((0, 0), window=msg_frame, anchor='nw', width=chat_canvas.winfo_reqwidth())

# resize canvas to fit to frame and update its scrollregion
def on_msg_frame_configure(event):
    # set canvas size as new 'stretched' frame size
    chat_canvas.configure(height=msg_frame.winfo_reqheight())
    chat_canvas.configure(scrollregion=chat_canvas.bbox('all'))

# my (not working) attempt to resize the blue msg_frame 
def on_top_frame_configure(event):
    msg_frame.configure(width=top_frame.winfo_reqwidth(), height=top_frame.winfo_reqheight())


# binds to resize widgets when root size changes
msg_frame.bind(sequence='<Configure>', func=on_msg_frame_configure)
top_frame.bind(sequence='<Configure>', func=on_top_frame_configure) # <-- not working

标签: pythontkinterresize

解决方案


经过多次尝试,我设法得到了我想要的。这就是我所做的:

创建窗口时,为其分配一个变量

canvas_frame = chat_canvas.create_window((0, 0), window=msg_frame, anchor='nw', tags="msg_frame")

然后使用以下配置函数绑定小部件:


def on_chat_canvas_configure(event):
    # set canvas size as new 'stretched' frame size
    chat_canvas.itemconfig(canvas_frame, width=event.width)
    canvas_scrollbar.pack_configure(side='right', fill='y')
    chat_canvas.pack_configure(side='right', fill='both', expand=True)


def on_msg_frame_configure(event):
    print('on msg frame')
    chat_canvas.configure(scrollregion=chat_canvas.bbox('msg_frame'))

# binds
chat_canvas.bind('<Configure>', lambda e: on_chat_canvas_configure(e))
msg_frame.bind('<Configure>', lambda e: on_msg_frame_configure(e))

当根窗口大小改变时,画布的大小也会改变,并且配置事件会触发,调用on_chat_canvas_configure()改变画布宽度的函数msg_frame,同时保持滚动条和画布的大小相对于根窗口。

当大小发生msg_frame变化时,此小部件的配置事件将触发并调用on msg_frame_configure()仅更新scrollregion画布的函数。

希望我正确而清晰地解释了逻辑。


推荐阅读