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

如何调整ipywidgets中interact生成的输入框宽度?

解决ipywidgets中interact输入框宽度不足的问题

当使用interact函数生成文本输入框时,默认控件宽度有限,无法适配长字符串的便捷编辑需求,你可以通过以下两种方式解决:

方法一:自定义Text控件的宽度

手动指定interact的输入控件为ipywidgets.Text,通过layout参数设置宽度(支持像素、百分比等单位),同时可直接获取修改后的内容:

import re
from ipywidgets import interact, Text

x1 = """The Supreme Court, in the matter of, held that moratorium  mentioned in section 141 Chapter XVII of the Act. / उच्चतम न्यायालय ने 

Dwarkadhish Sakhar Karkhana Ltd. Vs. Pankaj Joshi and Anr. / द्वारकाधीश 
Kalpraj Dharamshi & Anr. Vs. Kotak Investment Advisors Ltd. & Anr. / कल्पराज""" 

# 移除非英文字符
x2 = re.sub(r'[^\x00-\x7f]', r'', x1)

def f(x):
    return x

# 自定义Text控件,设置宽度为800px(也可设为'100%'占满容器)
text_widget = Text(value=x2, layout={'width': '800px'})
w = interact(f, x=text_widget)

# 获取修改后的值
modified_value = w.widget.x.value

方法二:改用Textarea控件(适配多行长文本)

如果字符串包含换行或内容极长,Textarea控件更适合,它支持多行编辑,同时可自定义宽高:

import re
from ipywidgets import interact, Textarea

x1 = """The Supreme Court, in the matter of, held that moratorium  mentioned in section 141 Chapter XVII of the Act. / उच्चतम न्यायालय ने 

Dwarkadhish Sakhar Karkhana Ltd. Vs. Pankaj Joshi and Anr. / द्वारकाधीश 
Kalpraj Dharamshi & Anr. Vs. Kotak Investment Advisors Ltd. & Anr. / कल्पराज""" 

x2 = re.sub(r'[^\x00-\x7f]', r'', x1)

def f(x):
    return x

# 设置Textarea的宽度和高度,比如宽度100%,高度200px
textarea_widget = Textarea(value=x2, layout={'width': '100%', 'height': '200px'})
w = interact(f, x=textarea_widget)

# 获取修改后的值
modified_value = w.widget.x.value

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:20:00