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

PyCharm运行Tkinter代码无窗口弹出,程序瞬间关闭如何解决?

Tkinter窗口瞬间关闭的解决方法

你的代码存在两个关键问题:

  1. 缺少Tkinter的主事件循环,程序执行完所有代码后直接退出,导致窗口一闪而过
  2. 创建的按钮控件未进行布局,即便窗口正常显示,按钮也不会出现

修正方案:

  • 在代码末尾添加mainwindow.mainloop(),这行代码会启动Tkinter的事件循环,让程序持续运行并保持窗口显示
  • 给按钮添加布局方法,比如buttonOne.pack()(也可根据需求使用grid()或place())

修正后的完整代码:

import tkinter
mainwindow=tkinter.Tk()
mainwindow.title("Calculator")
mainwindow.geometry('480x240')
buttonOne= tkinter.Button(mainwindow,text='1')
buttonOne.pack()
mainwindow.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:05:32