| import gradio as gr |
| import pandas as pd |
|
|
| |
| data = { |
| "姓名": ["张三", "李四", "王五", "赵六"], |
| "岗位": ["高级算法工程师", "前端开发专家", "产品经理", "数据分析师"], |
| "个人简介": [ |
| "负责大语言模型微调与落地,拥有多年AI研发经验。", |
| "精通Vue/React/Svelte,热衷于极致的用户体验与前端性能优化。", |
| "负责数据中台产品线,喜欢钻研用户痛点与商业闭环。", |
| "专注于商业数据挖掘与可视化看板建设,用数据驱动业务增长。" |
| ], |
| } |
| df = pd.DataFrame(data) |
|
|
| |
| js_drag_column_width = """ |
| function() { |
| const observer = new MutationObserver(() => { |
| const ths = document.querySelectorAll('.gradio-container th'); |
| if (ths.length === 0) return; |
| |
| ths.forEach(th => { |
| if (th.querySelector('.resizer')) return; |
| |
| const resizer = document.createElement('div'); |
| resizer.className = 'resizer'; |
| resizer.style.position = 'absolute'; |
| resizer.style.right = '0'; |
| resizer.style.top = '0'; |
| resizer.style.width = '6px'; |
| resizer.style.height = '100%'; |
| resizer.style.cursor = 'col-resize'; |
| resizer.style.userSelect = 'none'; |
| resizer.style.zIndex = '1'; |
| |
| th.style.position = 'relative'; |
| th.appendChild(resizer); |
| |
| let startX, startWidth; |
| |
| resizer.addEventListener('mousedown', function(e) { |
| startX = e.pageX; |
| startWidth = th.offsetWidth; |
| |
| function doDrag(ev) { |
| th.style.width = (startWidth + (ev.pageX - startX)) + 'px'; |
| th.style.minWidth = (startWidth + (ev.pageX - startX)) + 'px'; |
| } |
| |
| function stopDrag() { |
| document.removeEventListener('mousemove', doDrag); |
| document.removeEventListener('mouseup', stopDrag); |
| } |
| |
| document.addEventListener('mousemove', doDrag); |
| document.addEventListener('mouseup', stopDrag); |
| e.preventDefault(); |
| }); |
| }); |
| }); |
| |
| observer.observe(document.body, { childList: true, subtree: true }); |
| } |
| """ |
|
|
| |
| custom_css = """ |
| .resizer:hover { |
| background: #FF5722 !important; |
| width: 4px !important; |
| } |
| .gradio-container table { |
| table-layout: fixed; |
| width: 100%; |
| } |
| /* 给 dataframe 容器加上固定高度和滚动条,代替旧版的 height=400 */ |
| .custom-table-container .table-wrap { |
| max-height: 400px; |
| overflow-y: auto; |
| } |
| """ |
|
|
| |
| with gr.Blocks() as demo: |
| gr.Markdown("### 💡 Gradio 6.0 Dataframe 鼠标拖拽改变列宽示例") |
| gr.Markdown("您可以把鼠标放到**表头列与列的交界处**,按住鼠标左键左右拖拽即可调整这一列的宽度。") |
| |
| |
| with gr.Row(elem_classes="custom-table-container"): |
| gr.Dataframe( |
| value=df, |
| interactive=True, |
| wrap=False |
| ) |
|
|
| if __name__ == "__main__": |
| |
| demo.launch(css=custom_css, js=js_drag_column_width) |