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

如何用Python Tkinter实现Next按钮循环展示JSON数据集

公交数据GUI切换问题解决方案

问题描述

需要实现以下功能:

  • 读取JSON格式的公交到站数据
  • 用Tkinter创建GUI,程序启动时显示第一组公交数据
  • 点击「Next」按钮,依次切换显示后续各组数据,预期启动显示127#13:21:17#13:34:30,点击Next后显示168#13:16:50#13:30:35,以此类推。

用户提供的原代码未能实现上述功能,以下是原代码:

原test.py代码

import tkinter as tk
import json

f = open('bus_arrival.json')
myJSON = json.load(f)

window = tk.Tk()
canvas = tk.Canvas(window, width=300, height=80)
canvas.pack()
window.title("Hello World")
    
def next_btn():  
    print("test")

button = tk.Button(text='Next', command=next_btn)
canvas.create_window(230, 20, window=button)

# the result is a Python dictionary:
for ad in myJSON["bus"]:
    text = tk.Label(window, text=ad["Bus Service"] + "#" + ad["1st Bus"] + "#" + ad["2nd Bus"])
    canvas.create_window(150, 20, window=text)

window.mainloop()

原bus_arrival.json代码

{
    "bus": [
        {
            "Bus Service": "127",
            "1st Bus": "13:21:17",
            "2nd Bus": "13:34:30"
        },
        {
            "Bus Service": "168",
            "1st Bus": "13:16:50",
            "2nd Bus": "13:30:35"
        },
        {
            "Bus Service": "27",
            "1st Bus": "13:12:38",
            "2nd Bus": "13:21:00"
        },
        {
            "Bus Service": "72",
            "1st Bus": "13:13:24",
            "2nd Bus": "13:20:45"
        },
        {
            "Bus Service": "",
            "1st Bus": "",
            "2nd Bus": ""
        }
    ]
}

问题分析

原代码存在以下问题:

  • 循环创建了所有Label并叠加在同一位置,导致只能看到最后一组数据
  • Next按钮的回调函数未实现数据切换逻辑,仅打印测试信息
  • 没有跟踪当前显示的数据集索引,无法实现顺序切换

修正后的代码

import tkinter as tk
import json

# 用with语句读取JSON文件,自动关闭文件更安全
with open('bus_arrival.json', 'r', encoding='utf-8') as f:
    myJSON = json.load(f)

window = tk.Tk()
canvas = tk.Canvas(window, width=300, height=80)
canvas.pack()
window.title("公交到站查询")

# 跟踪当前显示的数据集索引,初始为0(第一组)
current_index = 0
bus_data = myJSON["bus"]

# 创建单个Label用于显示数据,后续只更新内容
text_label = tk.Label(window, text="")
canvas.create_window(150, 20, window=text_label)

def update_label():
    """更新Label显示当前索引对应的公交数据"""
    ad = bus_data[current_index]
    display_text = f"{ad['Bus Service']}#{ad['1st Bus']}#{ad['2nd Bus']}"
    text_label.config(text=display_text)

def next_btn():
    """Next按钮回调:切换到下一组数据"""
    global current_index
    # 检查是否还有下一组数据(避免索引越界)
    if current_index < len(bus_data) - 1:
        current_index += 1
        update_label()

# 创建Next按钮
button = tk.Button(text='Next', command=next_btn)
canvas.create_window(230, 20, window=button)

# 初始化显示第一组数据
update_label()

window.mainloop()

关键改动说明

  1. 文件读取优化:使用with语句读取JSON文件,无需手动关闭文件,避免资源泄漏
  2. 单个Label复用:只创建一个Label组件,通过config(text=...)方法更新显示内容,避免组件叠加
  3. 索引跟踪:用current_index变量记录当前显示的数据集位置,点击Next时递增索引(并做边界检查,防止越界)
  4. 拆分逻辑:将更新Label的逻辑封装为update_label函数,代码更清晰易维护
  5. 初始化显示:程序启动时调用update_label,直接显示第一组数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:19:50