You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整Tkinter的Text组件尺寸?设置height/width后组件消失求助

解决Tkinter Text组件设置height/width后消失的问题

问题出在布局配置上:你给Text组件加了sticky='NSWE'让它拉伸填充单元格,但没有给主窗口的行列设置权重(weight),当手动指定height和width时,布局管理器的拉伸规则和固定尺寸发生冲突,导致组件被挤压至消失。

解决方案

  1. 给主窗口的行列设置权重,让布局管理器明确空间分配规则
  2. 结合height/width设置组件初始尺寸,同时保留窗口拉伸时的自适应能力

修改后的完整代码

import tkinter as tk 
from tkinter import * 
from tkinter import ttk


class App(object):
    def __init__(self, master, **kwarg):
        self.master = master
        self.open_chat()
        
    def open_chat(self):    
        # 设置Text组件的初始height和width
        self.textbox = tk.Text(self.master, wrap=WORD, height=5, width=80)
        self.chatbox = tk.Text(self.master, wrap="word", height=20, width=80)
        
        scroll = ttk.Scrollbar(self.master)
        send = ttk.Button(self.master, text="Send", command=self.send_a_message)
        
        scroll.config(command=self.chatbox.yview)
        self.chatbox.config(yscrollcommand=scroll.set, state="disabled")
        
        # 配置主窗口的行列权重,控制空间分配比例
        self.master.grid_columnconfigure(0, weight=1)  # 第0列占绝大多数宽度
        self.master.grid_rowconfigure(0, weight=3)     # 聊天框所在行占3/4高度
        self.master.grid_rowconfigure(1, weight=1)     # 输入框所在行占1/4高度
        
        self.chatbox.grid(column=0, row=0, sticky='NSWE')
        self.textbox.grid(column=0, row=1, sticky='NSWE')
        send.grid(column=1, row=1, sticky='NSW')
        scroll.grid(column=1, row=0, sticky='NSW')

    def send_a_message(self):
        self.chatbox.config(state="normal")
        content = self.textbox.get('1.0','end')
        self.chatbox.insert(END, content)
        self.chatbox.config(state="disabled")
        self.textbox.delete('1.0',END)

win = tk.Tk()
win.title('My program')
win.minsize(1000,500)
app = App(win)
win.mainloop()

额外说明

  • grid_columnconfigure和grid_rowconfigure的weight值是空间分配比例,比如行0权重为3、行1为1,窗口高度变化时,行0会获得3/4的新增空间,行1获得1/4
  • 如果想要组件完全固定尺寸,可以去掉sticky='NSWE',但窗口拉伸时组件不会跟随放大

内容的提问来源于stack exchange,提问作者Misaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 20:23:20