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

Tkinter使用.place方法布局按钮时界面缩小、控件堆叠且出现背景文本框

问题核心错误&修复方案
  • 容器类型错误:你把用于多页面切换的容器f1/f2/s定义为了tk.Entry输入框组件,而非tk.Frame容器组件,这是界面出现多余文本框、按钮堆叠的核心原因,Entry本身是单行输入控件,无法作为容器正常承载多个子组件。
  • 容器拉伸配置缺失:你没有给主窗口的网格行列设置权重,即使给容器加了sticky='news',容器也无法自动撑满整个窗口,导致子组件都挤在极小的输入框区域内。
  • 坐标参数异常:部分组件的place坐标超出了窗口范围(比如退出按钮y设为-50、菜单标签y设为300,你的窗口总高度才200),导致这些组件无法正常显示。
  • 无用赋值:place()方法返回值为None,把place操作赋值给b1、b2等变量没有实际意义,可以直接去掉赋值操作。

修复后可正常运行的代码

import tkinter as tk
from tkinter import *
import os


def raise_frame(frame):
    frame.tkraise()


root = tk.Tk()
root.geometry('300x200')
root.title('o')

# 改为Frame容器,而非Entry
f1 = tk.Frame(root)
f2 = tk.Frame(root)
s = tk.Frame(root)

root.resizable(width=False, height=False)
# 给主窗口的行0、列0设置权重,让容器可以撑满窗口
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

# 所有容器都放在同一个网格位置,后续靠tkraise切换显示
for frame in (f1, f2, s):
    frame.grid(row=0, column=0, sticky='news')


clicks = IntVar()
inc = IntVar()


def increase(event=None):
    inc.set(inc.get() + 1)


def clicked(event=None):
   clicks.set(clicks.get() + inc.get())


#img = PhotoImage(file='Assets\c.png')
#gc = tk.Label(f2,image=img).place(x=10, y=10)

#menu frame 调整坐标到窗口可见范围内
tk.Button(f1,text='Go to game', fg="dark green", bg="white", command=lambda:raise_frame(f2)).place(x=5, y=10)
tk.Button(f1, text='Quit', fg="red", bg="white", command=lambda:quit()).place(x=5, y=40)
tk.Label(f1, text='Menu', fg="dark green").place(x=20, y=70)

#game frame
tk.Label(f2, text='Game', fg="dark green").place(x=1, y=1)
tk.Button(f2, text='Return to menu', fg="dark green", bg="white", command=lambda:raise_frame(f1)).place(x=10, y=30)
tk.Button(f2, text='Go to the shop', fg="dark green", bg="white", command=lambda:raise_frame(s)).place(x=10, y=60)
tk.Button(f2, text="Increase", command=clicked, fg="dark green", bg="white").place(x=50, y=90)
tk.Label(f2, textvariable=clicks, fg="dark green").place(x=50, y=120)

#shop frame
tk.Label(s, text='The shop', fg="dark green").place(x=1, y=1)
tk.Button(s, text='Return', fg="dark green", bg="white", command=lambda:raise_frame(f2)).place(x=10, y=30)
tk.Button(s, text="Test (+2 ppc)", command=increase, fg="dark green", bg="white").place(x=10, y=60)
tk.Label(s, text="当前点击数:", fg="dark green").place(x=10, y=90)
tk.Label(s, textvariable=clicks, fg="dark green").place(x=90, y=90)
tk.Label(s, text="单次点击增量:", fg="dark green").place(x=10, y=120)
tk.Label(s, textvariable=inc, fg="dark green").place(x=110, y=120)

raise_frame(f1)
root.mainloop()

内容的提问来源于stack exchange,提问作者Elliott Blyth Larrubia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:24:04