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

Tkinter布局疑问:如何让输入框、按钮与居中图像同处屏幕中央

问题:让Tkinter中的输入框、按钮与图片一同居中显示

当前代码实现了图片在屏幕中央,但Entry输入框和Button按钮被挤到了屏幕底部,需要调整布局让这三个控件一起处于屏幕中央。

原代码:

from tkinter import *

fenetre = Tk()

width = 350
height = 299
image = PhotoImage(file="carre.png")
canvas = Canvas(fenetre, width=width, height=height, bd=0, highlightthickness=0)
canvas.create_image(width/2, height/2, image=image, anchor=CENTER)
canvas.pack(expand=YES)
entree = Entry(fenetre, font=("sans-serif",20))
entree.pack()
bouton = Button(fenetre, text="CALCULER", font=("sans-serif",20), fg = "black") # fg = foreground
bouton.pack()
bouton.bind("<Button-1>")

fenetre.mainloop()

解决方案

问题出在canvas.pack(expand=YES)让Canvas控件占满了窗口的可用空间,后续的Entry和Button只能被挤到窗口底部。我们可以把所有需要居中的控件放到一个容器Frame里,再让这个Frame整体居中,就能实现所有控件一起居中的效果。

修改后的代码:

from tkinter import *

fenetre = Tk()

# 创建容器Frame,统一管理需要居中的控件
main_frame = Frame(fenetre)
main_frame.pack(expand=YES)  # 让容器在窗口中居中

width = 350
height = 299
image = PhotoImage(file="carre.png")
canvas = Canvas(main_frame, width=width, height=height, bd=0, highlightthickness=0)
canvas.create_image(width/2, height/2, image=image, anchor=CENTER)
canvas.pack()

entree = Entry(main_frame, font=("sans-serif",20))
entree.pack(pady=10)  # 增加垂直间距,优化布局美观度

bouton = Button(main_frame, text="CALCULER", font=("sans-serif",20), fg="black")
bouton.pack()
# 补充绑定示例函数(实际可替换为业务逻辑)
def calculer_action(event):
    print("计算按钮被触发")
bouton.bind("<Button-1>", calculer_action)

fenetre.mainloop()

关键说明

  1. 新增main_frame作为容器,将所有需要居中的控件父对象改为该Frame,确保它们属于同一布局组。
  2. main_frame.pack(expand=YES)让容器自动在窗口中居中,随窗口大小调整位置。
  3. pady=10为输入框增加上下间距,避免控件堆叠过于紧凑。
  4. 原代码中bind缺少处理函数,这里补充了示例逻辑,实际使用可按需替换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:20:30