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

如何将Tkinter按钮从底部中间移至侧边?网格布局失效问题

问题原因及解决方法

你的按钮没移动的核心问题是同一个父容器里混用了pack和grid布局:root容器里已经用pack放置了滚动条和文本框,再给calculater按钮用grid会导致Tkinter布局冲突,按钮无法正常显示位置。

要把按钮移到侧边,按以下步骤修改:

  1. 创建专门的侧边容器(Frame)来放按钮,避免和主区域的布局冲突
  2. 调整主文本区域的布局,让它占满剩余空间
  3. 将按钮放到侧边容器中,用合适的布局方式

修改后的完整代码:

import re
from tkinter import *
from tkinter import ttk
import time

root = Tk()
root.title('Notepad')
root.iconbitmap('C:/Users/Hero/Documents/Visual Studio code/My project/notes.ico')
root.geometry("500x500")

root.tk.call("source", "C:/Users/Hero/Documents/Visual Studio code/My project/azure.tcl")
root.tk.call("set_theme", "dark")

def change_theme():
    if root.tk.call("ttk::style", "theme", "use") == "azure-dark":
        root.tk.call("set_theme", "light")
    else:
        root.tk.call("set_theme", "dark")

style=ttk.Style()
style.theme_use('azure-dark')
style.configure("Vertical.TScrollbar", background="grey", bordercolor="black", arrowcolor="white")

# 1. 创建侧边框架,固定在窗口左侧并垂直填充
side_frame = Frame(root)
side_frame.pack(side=LEFT, fill=Y, padx=5, pady=5)

# 2. 底部框架保持不变
barframe = Frame(root)
barframe.pack(side=BOTTOM, fill=X, padx=5, pady=5)

# 3. 调整文本区域和滚动条布局,让文本框占满剩余空间
scroll = ttk.Scrollbar(root, orient='vertical')
scroll.pack(side=RIGHT, fill='y')

text=Text(root, font=("Georgia, 24"), yscrollcommand=scroll.set, bg='#292929')
scroll.config(command=text.yview)
# 用fill=BOTH和expand=True让文本框填充剩余的水平+垂直空间
text.pack(side=RIGHT, fill=BOTH, expand=True)

# 4. 把按钮放到对应框架里
fonts = ttk.Button(barframe, text='Size and Font', width=15, style='Accent.TButton')
calculater = ttk.Button(side_frame, text='Calculater', width=15, style='Accent.TButton')

# 底部按钮垂直居中
fonts.pack(pady=5)
# 侧边按钮垂直居中(也可以用grid调整位置)
calculater.pack(pady=20)

root.mainloop()

关键改动说明

  • 新增side_frame作为侧边按钮的容器,用pack(side=LEFT, fill=Y)固定在左侧并垂直填充
  • 文本框添加fill=BOTH, expand=True,确保它占满窗口除侧边框架和底部框架外的所有空间
  • 将calculater按钮的父容器从root改为side_frame,彻底避免布局冲突
  • 底部的fonts按钮用pack(pady=5)实现垂直居中,单按钮场景比grid更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:15:36