【发布时间】: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
【问题讨论】: