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

Python项目问题:函数传参及月度团队人均工单计算

Tkinter+Pandas+Matplotlib 项目问题解决方案

问题概述

  • 无法将Tkinter下拉框选择的团队参数传入函数,直接调用会因无参数报错
  • 无法按月份统计指定团队的工单处理用户数,导致每月人均工单量计算错误

修改后的完整代码

import pandas as pd
import matplotlib.pyplot as plt
from tkinter import *

# 读取数据
excel = 'new_export.xlsx'
data = pd.read_excel(excel, parse_dates=['Closed Date Time'])
df = pd.DataFrame(data)

# 日期格式处理:提取日期部分并生成年月字段
df['Close_Date'] = pd.to_datetime(data['Closed Date Time']).dt.date
df['Close_Date'] = pd.to_datetime(df['Close_Date'])
df['Year_Month'] = df['Close_Date'].dt.strftime('%Y-%m')

# -------------------- GUI 部分 ------------------
root = Tk()
root.title("团队人均工单量统计")
root.geometry('400x200')

# -------------------- 功能函数 ---------------------------- #
def calculate_monthly_avg(selected_team):
    # 筛选指定团队的工单数据
    team_data = df[df['Owned By Team'] == selected_team]
    # 统计每月工单总数量
    monthly_tickets = team_data.groupby('Year_Month').size()
    # 统计每月参与处理的唯一用户数
    monthly_users = team_data.groupby('Year_Month')['Owned By'].nunique()
    # 计算人均工单量,避免除以0的情况
    monthly_avg = monthly_tickets / monthly_users.replace(0, 1)
    return monthly_avg

def show_graph():
    # 获取下拉框选中的团队
    selected_team = clicked.get()
    if not selected_team:
        return  # 未选择团队时直接返回,避免报错
    # 获取计算后的月度人均数据
    monthly_avg = calculate_monthly_avg(selected_team)
    # 绘制图表
    plt.style.use("featherweight")
    monthly_avg.plot(kind='bar')
    plt.title(f'{selected_team} 每月人均工单量')
    plt.xlabel('年份-月份')
    plt.ylabel('人均工单量')
    plt.xticks(rotation=45)
    plt.tight_layout()  # 自动调整布局,防止标签被截断
    plt.show()

# 下拉框:加载所有团队选项
team_options = sorted(set(df['Owned By Team']))
clicked = StringVar()
# 默认选中第一个团队(可选)
if team_options:
    clicked.set(team_options[0])
drop = OptionMenu(root, clicked, *team_options)
drop.pack(pady=10)

# 显示图表按钮
newGraph = Button(root, text='生成图表', command=show_graph)
newGraph.pack(pady=10)

root.mainloop()

关键修改说明

1. 解决参数传递问题

  • 重命名函数为更清晰的名称(calculate_monthly_avg、show_graph)
  • show_graph函数直接从clicked.get()获取下拉框选中的团队,避免参数传递报错
  • 增加空值判断:未选择团队时直接返回,防止触发无效计算

2. 实现按月份统计用户数并计算人均

  • 先筛选指定团队的所有数据,再按Year_Month分组
  • 使用groupby('Year_Month')['Owned By'].nunique()统计每月的唯一用户数(自动去重)
  • 计算人均工单量时,用replace(0,1)避免出现除以0的报错(当某月份无工单时)
  • 将图表类型从直方图改为柱状图,更适合展示月度趋势数据,同时优化图表布局和标签显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:40:38