【问题标题】:is it possible to stretch create_window() frame to size of parent (or root)?是否可以将 create_window() 框架拉伸到父(或根)的大小?
【发布时间】:2021-01-18 14:37:34
【问题描述】:

我想让我的聊天室应用 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

【问题讨论】:

    标签: python tkinter resize


    【解决方案1】:

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

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

    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

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

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 2011-11-24
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2012-04-11
      • 2016-12-02
      • 1970-01-01
      相关资源
      最近更新 更多