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

Tkinter无法打印全部所需行星数据仅显示最后一条的问题咨询

问题原因

你当前代码的问题是循环中每次调用Infomation.config(text=xxx)都会直接覆盖控件上已有的文本内容,所以循环结束后只会保留最后一次赋值的行星数据。

解决方案

方案1:使用Label控件实现(适合内容少不需要滚动的场景)

先把所有行星信息拼接成带换行的完整字符串,再一次性给控件赋值即可实现逐行展示:

def infomation(day_count, planets):
    Day.config(text=day_count)
    # 初始化空字符串存储所有行星信息
    all_info = ""
    for planet in planets:
        # 每条信息末尾加换行符实现逐行分隔
        all_info += '{:<8} posision (m)  x ={:6.2f}  y ={:6.2f} velocity (m/s)  x ={:9.2f}  y = {:9.2f} \n'.format(
                planet.planet_name, planet.pos_x/AU, planet.pos_y/AU, planet.velocity_x, planet.velocity_y)
    # 一次性赋值所有内容
    Infomation.config(text=all_info)

方案2:使用Text控件实现(适合内容多需要滚动查看的场景)

如果行星数量较多,建议把原来的Infomation控件从Label替换为Text控件,插入内容的写法如下:

def infomation(day_count, planets):
    Day.config(text=day_count)
    # 先清空控件原有内容
    Infomation.delete(1.0, "end")
    for planet in planets:
        info_str = '{:<8} posision (m)  x ={:6.2f}  y ={:6.2f} velocity (m/s)  x ={:9.2f}  y = {:9.2f} \n'.format(
                planet.planet_name, planet.pos_x/AU, planet.pos_y/AU, planet.velocity_x, planet.velocity_y)
        # 逐行插入到Text控件末尾
        Infomation.insert("end", info_str)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:15:06