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

Tk对象无法转为整数错误:经济数据仪表盘函数传参求助

问题

开发经济数据仪表盘项目时,调用Plot_data函数持续报错,无法将下拉框返回的start_year和end_year参数正确传入函数,报错信息为:

TypeError: 'Tk' object cannot be interpreted as an integer

完整代码

from tkinter import *
from PIL import Image, ImageTk
from tkinter.ttk import Label
import matplotlib.pyplot as plt
import wbgapi as wb

root = Tk()
root.title("Dashboard")
root.geometry("1920x1080")
root.configure(bg="#555358")
start_year = 2010
end_year = 2022

def display_titles(root):
    Title1 = Label(root, background="#555358", foreground="white", text="Interest Rate", font=("ariel Rounded MT Bold", 28))
    Title3 = Label(root, background="#555358", foreground="white", text="Unemployment", font=("ariel Rounded MT Bold", 28))
    Title4 = Label(root, background="#555358", foreground="white", text="National Debt", font=("ariel Rounded MT Bold", 28))
    Title5 = Label(root, background="#555358", foreground="white", text="Gross Domestic Product", font=("ariel Rounded MT Bold", 28))
    Title6 = Label(root, background="#555358", foreground="white", text="Consumer Price Index", font=("ariel Rounded MT Bold", 28))
    Title1.place(x=233, y=44, anchor="c")
    Title3.place(x=1133, y=44, anchor="c")
    Title4.place(x=233, y=374, anchor="c")
    Title5.place(x=683, y=374, anchor="c")
    Title6.place(x=1133, y=374, anchor="c")

def Plot_data(start_year, end_year):
    wbgapi_id = {
    "Interest": "FP.CPI.TOTL.ZG",
    "GDP": "NY.GDP.MKTP.KD.ZG",
    "CPI": "FP.CPI.TOTL",
    "National Debt": "GC.DOD.TOTL.CN",
    "Unemployment": "SL.UEM.TOTL.ZS",
    }
        # This function plots the data from WGB API
    graph1 = wb.data.DataFrame(wbgapi_id["Interest"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_one.png')

    # Graph 2 was repalced earlier and replaced with a navigation menu

    graph3 = wb.data.DataFrame(wbgapi_id["Unemployment"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_three.png')

    graph4 = wb.data.DataFrame(wbgapi_id["National Debt"], 'GBR', range(2010, 2022), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_four.png')

    graph5 = wb.data.DataFrame(wbgapi_id["GDP"], 'GBR', range(2010, 2022), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_five.png')

    graph6 = wb.data.DataFrame(wbgapi_id["CPI"], 'GBR', range(2010, 2022), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_six.png')

def image(root):
    canvas1 = Canvas(root, height = 260, width = 400)
    canvas1.place(x=33, y=70) 
    img1 = Image.open("graph_one.png")
    canvas1.image = ImageTk.PhotoImage(img1)
    canvas1.create_image(200, 120, image = canvas1.image, anchor = "center")

    canvas2 = Canvas(root, height = 260, width = 400)
    canvas2.place(x=933, y=70)
    img2 = Image.open("graph_two.png")
    canvas2.image = ImageTk.PhotoImage(img2)
    canvas2.create_image(200, 120, image = canvas2.image, anchor = "center")

    canvas3 = Canvas(root, height = 260, width = 400)
    canvas3.place(x=33, y=400)
    img3 = Image.open("graph_three.png")
    canvas3.image = ImageTk.PhotoImage(img3)
    canvas3.create_image(200, 120, image = canvas3.image, anchor = "center")

    canvas4 = Canvas(root, height = 260, width = 400)
    canvas4.place(x=483, y=400)
    img4 = Image.open("graph_four.png")
    canvas4.image = ImageTk.PhotoImage(img4)
    canvas4.create_image(200, 120, image = canvas4.image, anchor = "center")

    canvas5 = Canvas(root, height = 260, width = 400)
    canvas5.place(x=933, y=400)
    img5 = Image.open("graph_five.png")
    canvas5.image = ImageTk.PhotoImage(img5)
    canvas5.create_image(200, 120, image = canvas5.image, anchor = "center")

def dropdown_end_year(root):
# End year selectrion below

    Endyears = ["2010","2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023"]
    var2 = StringVar()
    var2.set(Endyears[12])
    dropdown = OptionMenu(
        root,
        var2,
        *Endyears,
    )
    dropdown.place(x = 775, y = 150, anchor="c")
    end_year = var2.get()

    End_year_label = Label(root, text="End Year", background="#555358", foreground="white", font=("ariel Rounded MT", 20))
    End_year_label.place(x = 650, y = 150, anchor="c")
    return int(end_year)

def dropdown_start_year(root):
    # Start year selection generation below
    start_year_label = Label(root, text="Start Year", background="#555358", foreground="white", font=("ariel Rounded MT", 20))
    start_year_label.place(x = 650, y = 75, anchor="c")

    Startyears = ["2010","2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023"]
    var1 = StringVar()
    var1.set(Startyears[0])
    dropdown = OptionMenu(
        root,
        var1,
        *Startyears,
    )
    dropdown.place(x = 775, y = 75, anchor="c")
    start_year = var1.get()
    start_year = int(start_year)
    return start_year

display_titles(root)
dropdown_end_year(root)
dropdown_start_year(root)
Plot_data(dropdown_start_year(root), root)
image(root)

mainloop()

报错栈

Traceback (most recent call last):
  File "c:\Users\harry\OneDrive - Woodbridge School Email\Documents\Project\GUI.safe.py", line 129, in <module>
    Plot_data(dropdown_start_year(root), root)
  File "c:\Users\harry\OneDrive - Woodbridge School Email\Documents\Project\GUI.safe.py", line 39, in Plot_data
    graph1 = wb.data.DataFrame(wbgapi_id["Interest"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
TypeError: 'Tk' object cannot be interpreted as an integer

解决方案

问题根源

  1. 传参错误:调用Plot_data(dropdown_start_year(root), root)时,第二个参数传了root(Tk对象)而非dropdown_end_year(root)返回的年份整数,导致range(start_year, end_year)中的end_year是Tk对象,触发类型错误。
  2. 下拉框值无法实时更新:当前代码中下拉框的StringVar是局部变量,仅初始化时获取一次值,无法响应后续用户选择。
  3. 部分图表硬编码年份:graph4、graph5、graph6的年份固定为range(2010,2022),未使用传入的参数。

修复步骤

  1. 修正Plot_data调用参数,将第二个参数改为dropdown_end_year(root)。
  2. 将下拉框的StringVar设为全局变量,确保能实时获取用户选择的年份。
  3. 添加更新按钮,点击时触发数据获取、图表生成和画布刷新。
  4. 统一所有图表的年份参数,替换硬编码值。
  5. 优化图表刷新逻辑,添加文件存在检查避免崩溃。

修改后的完整代码

from tkinter import *
from PIL import Image, ImageTk
from tkinter.ttk import Label
import matplotlib.pyplot as plt
import wbgapi as wb
import os

root = Tk()
root.title("Dashboard")
root.geometry("1920x1080")
root.configure(bg="#555358")

# 全局变量存储下拉框选择的年份
var1 = StringVar(value="2010")
var2 = StringVar(value="2022")

def display_titles(root):
    Title1 = Label(root, background="#555358", foreground="white", text="Interest Rate", font=("ariel Rounded MT Bold", 28))
    Title3 = Label(root, background="#555358", foreground="white", text="Unemployment", font=("ariel Rounded MT Bold", 28))
    Title4 = Label(root, background="#555358", foreground="white", text="National Debt", font=("ariel Rounded MT Bold", 28))
    Title5 = Label(root, background="#555358", foreground="white", text="Gross Domestic Product", font=("ariel Rounded MT Bold", 28))
    Title6 = Label(root, background="#555358", foreground="white", text="Consumer Price Index", font=("ariel Rounded MT Bold", 28))
    Title1.place(x=233, y=44, anchor="c")
    Title3.place(x=1133, y=44, anchor="c")
    Title4.place(x=233, y=374, anchor="c")
    Title5.place(x=683, y=374, anchor="c")
    Title6.place(x=1133, y=374, anchor="c")

def Plot_data(start_year, end_year):
    wbgapi_id = {
        "Interest": "FP.CPI.TOTL.ZG",
        "GDP": "NY.GDP.MKTP.KD.ZG",
        "CPI": "FP.CPI.TOTL",
        "National Debt": "GC.DOD.TOTL.CN",
        "Unemployment": "SL.UEM.TOTL.ZS",
    }
    # 生成所有图表,统一使用传入的年份参数
    plt.figure()
    wb.data.DataFrame(wbgapi_id["Interest"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_one.png')
    plt.close()

    plt.figure()
    wb.data.DataFrame(wbgapi_id["Unemployment"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_three.png')
    plt.close()

    plt.figure()
    wb.data.DataFrame(wbgapi_id["National Debt"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_four.png')
    plt.close()

    plt.figure()
    wb.data.DataFrame(wbgapi_id["GDP"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_five.png')
    plt.close()

    plt.figure()
    wb.data.DataFrame(wbgapi_id["CPI"], 'GBR', range(start_year, end_year), index='time', numericTimeKeys=True, labels=True).plot(figsize=(4, 3))
    plt.savefig('graph_six.png')
    plt.close()

def update_dashboard():
    # 获取当前下拉框选择的年份
    start_year = int(var1.get())
    end_year = int(var2.get())
    # 生成图表
    Plot_data(start_year, end_year)
    # 刷新画布显示
    image(root)

def image(root):
    # 定义画布和对应图片的映射
    canvas_map = {
        "graph_one.png": (33, 70),
        "graph_three.png": (33, 400),
        "graph_four.png": (483, 400),
        "graph_five.png": (933, 400),
        "graph_six.png": (933, 70)  # 原graph_two位置替换为CPI图表
    }

    for img_name, (x, y) in canvas_map.items():
        # 检查图片文件是否存在
        if os.path.exists(img_name):
            canvas = Canvas(root, height=260, width=400, bg="#555358", highlightthickness=0)
            canvas.place(x=x, y=y)
            img = Image.open(img_name)
            canvas.image = ImageTk.PhotoImage(img)
            canvas.create_image(200, 120, image=canvas.image, anchor="center")

def dropdown_end_year(root):
    Endyears = ["2010","2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023"]
    dropdown = OptionMenu(root, var2, *Endyears)
    dropdown.place(x=775, y=150, anchor="c")
    End_year_label = Label(root, text="End Year", background="#555358", foreground="white", font=("ariel Rounded MT", 20))
    End_year_label.place(x=650, y=150, anchor="c")

def dropdown_start_year(root):
    Startyears = ["2010","2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023"]
    dropdown = OptionMenu(root, var1, *Startyears)
    dropdown.place(x=775, y=75, anchor="c")
    start_year_label = Label(root, text="Start Year", background="#555358", foreground="white", font=("ariel Rounded MT", 20))
    start_year_label.place(x=650, y=75, anchor="c")

# 创建更新按钮
update_btn = Button(root, text="Update Data", command=update_dashboard, font=("ariel Rounded MT", 16), bg="#2c3e50", fg="white")
update_btn.place(x=775, y=225, anchor="c")

display_titles(root)
dropdown_end_year(root)
dropdown_start_year(root)
# 初始化生成一次图表
update_dashboard()

mainloop()

说明

  • 新增update_dashboard函数作为按钮回调,负责获取最新年份、生成图表、刷新画布
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:55:22