Foreword: the recent feel more and more disorderly code, all kinds of variable names with function let me confused, estimated after writing this, I want to take some time to sort out to consolidate the basic knowledge and finish the following these bloated code, pause time under the train of thought, since found himself should go to make up for the deficiency of the, not ignored. The following code compared with the last time to add the market index index information display, add the market K-line style attribute, the other seems to have no change, the code renderings are as follows:

PS: If you need Python learning materials, please click on the link below to obtain them

Free Python learning materials and group communication solutions click to join

import pandas as pd
import tushare as ts
import mplfinance as mpf
import tkinter as tk
import tkinter.tix as tix
from tkinter import ttk
import tkinter.font as tf
from tkinter.constants import *
import matplotlib.pyplot as plt
import matplotlib.dates as mdates  # 处理日期
import matplotlib as mpl  # 用于设置曲线参数
from cycler import cycler  # 用于定制线条颜色
import datetime
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

pro = ts.pro_api('要到tushare官网注册个账户然后将token复制到这里,可以的话请帮个忙用文章末我分享的链接注册,谢谢')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# pd.set_option()就是pycharm输出控制显示的设置
pd.set_option('expand_frame_repr', False)  # True就是可以换行显示。设置成False的时候不允许换行
pd.set_option('display.max_columns', None)  # 显示所有列
# pd.set_option('display.max_rows', None)  # 显示所有行
pd.set_option('colheader_justify', 'centre')  # 显示居中

root = tk.Tk()  # 创建主窗口
screenWidth = root.winfo_screenwidth()  # 获取屏幕宽的分辨率
screenHeight = root.winfo_screenheight()
x, y = int(screenWidth / 4), int(screenHeight / 4)  # 初始运行窗口屏幕坐标(x, y),设置成在左上角显示
width = int(screenWidth / 2)  # 初始化窗口是显示器分辨率的二分之一
height = int(screenHeight / 2)
root.geometry('{}x{}+{}+{}'.format(width, height, x, y))  # 窗口的大小跟初始运行位置
root.title('Wilbur量化复盘分析软件')
# root.resizable(0, 0)  # 固定窗口宽跟高,不能调整大小,无法最大窗口化
root.iconbitmap('ZHY.ico')  # 窗口左上角图标设置,需要自己放张图标为icon格式的图片文件在项目文件目录下

main_window = tk.PanedWindow(root)  # 设置窗口管理,将主窗口分成左右两部分
main_window.pack(fill='both', expand=1)

main_frame = tk.Frame(main_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN, bg='#353535', bd=5,
                      borderwidth=4)
main_window.pack(fill=BOTH, expand=1)
main_window.add(main_frame)  # 将功能主框架添加到左边窗口

# 创建图形显示主框架
graphic_main_frame = tk.Frame(main_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN, bg='#353535',
                              bd=5, borderwidth=4)
main_window.pack(fill=BOTH, expand=0)
main_window.add(graphic_main_frame)  # 将查询主框架添加到右边窗口

def stockindex_function():
    # 必须添加以下控件销毁代码,不然点击一次按钮框架长生一次,显示的画面会多一次,你可以将下面的代码删除测试看下
    for widget_graphic_main_frame in graphic_main_frame.winfo_children():
        widget_graphic_main_frame.destroy()
    # 在右边窗口的graphic_main_frame框架下再创建窗口
    # opaqueresize该选项的值为 False,窗格的尺寸在用户释放鼠标的时候才更新到新的位置
    stockindex_information_window = tk.PanedWindow(graphic_main_frame, opaqueresize=False)
    stockindex_information_window.pack(fill=BOTH, expand=1)

    # 在company_information_window窗口下设置指数信息显示功能
    stockindex_text = tk.Text(stockindex_information_window, bg='white', undo=True, wrap=tix.CHAR)
    stockindex_information_window.add(stockindex_text, width=200)

    # 首先获取今天时间,然后先尝试获取今天的数据,然后今天返回空值,则获取昨天的数据显示
    now_time = datetime.datetime.now()
    # 转化成tushare的时间格式
    strf_time = now_time.strftime('%Y%m%d')
    shsz_index_dailybasic = pro.index_dailybasic(trade_date=strf_time, fields='ts_code,trade_date,total_mv, '
                                                                              'float_mv,total_share,float_share,'
                                                                              'free_share,turnover_rate,'
                                                                              'turnover_rate_f,pe,pb')
    sh_index_daily = pro.index_daily(ts_code='000001.SH', trade_date=strf_time)
    sz_index_daily = pro.index_daily(ts_code='399001.SZ', trade_date=strf_time)
    cy_index_daily = pro.index_daily(ts_code='399006.SZ', trade_date=strf_time)
    zx_index_daily = pro.index_daily(ts_code='399005.SZ', trade_date=strf_time)
    print(sh_index_daily)
    if shsz_index_dailybasic.empty:
        now_time = datetime.datetime.now() - datetime.timedelta(days=1)
        strf_time = now_time.strftime('%Y%m%d')
        shsz_index_dailybasic = pro.index_dailybasic(trade_date=strf_time, fields='ts_code,trade_date,total_mv, '
                                                                                  'float_mv,total_share,float_share,'
                                                                                  'free_share,turnover_rate,'
                                                                                  'turnover_rate_f,pe,pb')
        sh_index_daily = pro.index_daily(ts_code='000001.SH', trade_date=strf_time)
        sz_index_daily = pro.index_daily(ts_code='399001.SZ', trade_date=strf_time)
        cy_index_daily = pro.index_daily(ts_code='399006.SZ', trade_date=strf_time)
        zx_index_daily = pro.index_daily(ts_code='399005.SZ', trade_date=strf_time)
        print(sh_index_daily)
    # 数据处理,将ts_code作为索引,方便准确调用数据,保留两位小数
    shsz_index_dailybasic.set_index('ts_code', inplace=True)
    # 数据获取
    sh_total_mv = round(shsz_index_dailybasic.at['000001.SH', 'total_mv']/100000000, 2)  # 元转换成亿单位
    sh_float_mv = round(shsz_index_dailybasic.at['000001.SH', 'float_mv']/100000000, 2)
    sh_total_share = round(shsz_index_dailybasic.at['000001.SH', 'total_share']/10000000000, 2)  # 股转化成亿手
    sh_float_share = round(shsz_index_dailybasic.at['000001.SH', 'float_share']/10000000000, 2)
    sh_free_share = round(shsz_index_dailybasic.at['000001.SH', 'free_share']//10000000000, 2)
    sh_turnover_rate = shsz_index_dailybasic.at['000001.SH', 'turnover_rate']
    sh_pe = shsz_index_dailybasic.at['000001.SH', 'pe']
    sh_pb = shsz_index_dailybasic.at['000001.SH', 'pb']
    sh_close = sh_index_daily.at[0, 'close']
    sh_pre_close = sh_index_daily.at[0, 'pre_close']
    sh_pct_chg = sh_index_daily.at[0, 'pct_chg']
    sh_vol = round(sh_index_daily.at[0, 'vol']/100000000, 2)  # 手转化成亿手
    sh_amount = round(sh_index_daily.at[0, 'amount']/100000, 2)  # 千元转换成亿元

    # 数据调用
    # 在文本框第一行添加股票代码,文字红色,居中显示
    stockindex_text.insert(tk.INSERT, '上证指数')
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总市值(亿):')
    stockindex_text.insert(tk.INSERT, sh_total_mv)
    stockindex_text.tag_add('tag1', '1.0', '1.9')  # 设置选定的内容
    stockindex_text.tag_config('tag1', foreground='red', justify=CENTER)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通市值(亿):')
    stockindex_text.insert(tk.INSERT, sh_float_mv)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总股本(亿手):')
    stockindex_text.insert(tk.INSERT, sh_total_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, sh_float_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '自由流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, sh_free_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '换手率:')
    stockindex_text.insert(tk.INSERT, sh_turnover_rate)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市盈率:')
    stockindex_text.insert(tk.INSERT, sh_pe)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市净率:')
    stockindex_text.insert(tk.INSERT, sh_pb)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '收盘点位:')
    stockindex_text.insert(tk.INSERT, sh_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '昨日收盘点:')
    stockindex_text.insert(tk.INSERT, sh_pre_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '涨跌幅(%):')
    stockindex_text.insert(tk.INSERT, sh_pct_chg)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交量(亿手):')
    stockindex_text.insert(tk.INSERT, sh_vol)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交额(亿):')
    stockindex_text.insert(tk.INSERT, sh_amount)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.tag_add('content1', '2.0', 'end')  # 设置选定的内容
    stockindex_text.tag_config('content1', foreground='blue')

    sz_total_mv = round(shsz_index_dailybasic.at['399001.SZ', 'total_mv'] / 100000000, 2)  # 转换成亿单位
    sz_float_mv = round(shsz_index_dailybasic.at['399001.SZ', 'float_mv'] / 100000000, 2)
    sz_total_share = round(shsz_index_dailybasic.at['399001.SZ', 'total_share'] / 10000000000, 2)  # 转化成亿手
    sz_float_share = round(shsz_index_dailybasic.at['399001.SZ', 'float_share'] / 10000000000, 2)
    sz_free_share = round(shsz_index_dailybasic.at['399001.SZ', 'free_share'] // 10000000000, 2)
    sz_turnover_rate = shsz_index_dailybasic.at['399001.SZ', 'turnover_rate']
    sz_pe = shsz_index_dailybasic.at['399001.SZ', 'pe']
    sz_pb = shsz_index_dailybasic.at['399001.SZ', 'pb']
    sz_close = sz_index_daily.at[0, 'close']
    sz_pre_close = sz_index_daily.at[0, 'pre_close']
    sz_pct_chg = sz_index_daily.at[0, 'pct_chg']
    sz_vol = round(sz_index_daily.at[0, 'vol']/100000000, 2)  # 手转化成亿手
    sz_amount = round(sz_index_daily.at[0, 'amount']/100000, 2)  # 千元转换成亿元

    stockindex_text.insert(tk.INSERT, '深证指数')
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总市值(亿):')
    stockindex_text.insert(tk.INSERT, sz_total_mv)
    stockindex_text.tag_add('tag2', '15.0', '15.9')  # 设置选定的内容,
    stockindex_text.tag_config('tag2', foreground='red', justify=CENTER)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通市值(亿):')
    stockindex_text.insert(tk.INSERT, sz_float_mv)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总股本(亿手):')
    stockindex_text.insert(tk.INSERT, sz_total_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, sz_float_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '自由流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, sz_free_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '换手率:')
    stockindex_text.insert(tk.INSERT, sz_turnover_rate)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市盈率:')
    stockindex_text.insert(tk.INSERT, sz_pe)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市净率:')
    stockindex_text.insert(tk.INSERT, sz_pb)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '收盘点位:')
    stockindex_text.insert(tk.INSERT, sz_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '昨日收盘点:')
    stockindex_text.insert(tk.INSERT, sz_pre_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '涨跌幅(%):')
    stockindex_text.insert(tk.INSERT, sz_pct_chg)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交量(亿手):')
    stockindex_text.insert(tk.INSERT, sz_vol)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交额(亿):')
    stockindex_text.insert(tk.INSERT, sz_amount)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.tag_add('content2', '16.0', 'end')  # 设置选定的内容
    stockindex_text.tag_config('content2', foreground='DarkViolet')

    cy_total_mv = round(shsz_index_dailybasic.at['399006.SZ', 'total_mv'] / 100000000, 2)  # 转换成亿单位
    cy_float_mv = round(shsz_index_dailybasic.at['399006.SZ', 'float_mv'] / 100000000, 2)
    cy_total_share = round(shsz_index_dailybasic.at['399006.SZ', 'total_share'] / 10000000000, 2)  # 转化成亿手
    cy_float_share = round(shsz_index_dailybasic.at['399006.SZ', 'float_share'] / 10000000000, 2)
    cy_free_share = round(shsz_index_dailybasic.at['399006.SZ', 'free_share'] // 10000000000, 2)
    cy_turnover_rate = shsz_index_dailybasic.at['399006.SZ', 'turnover_rate']
    cy_pe = shsz_index_dailybasic.at['399006.SZ', 'pe']
    cy_pb = shsz_index_dailybasic.at['399006.SZ', 'pb']
    cy_close = sh_index_daily.at[0, 'close']
    cy_pre_close = cy_index_daily.at[0, 'pre_close']
    cy_pct_chg = cy_index_daily.at[0, 'pct_chg']
    cy_vol = round(cy_index_daily.at[0, 'vol']/100000000, 2)  # 手转化成亿手
    cy_amount = round(cy_index_daily.at[0, 'amount']/100000, 2)  # 千元转换成亿元

    stockindex_text.insert(tk.INSERT, '创业板指数')
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总市值(亿):')
    stockindex_text.insert(tk.INSERT, cy_total_mv)
    stockindex_text.tag_add('tag3', '29.0', '29.9')  # 设置选定的内容,
    stockindex_text.tag_config('tag3', foreground='red', justify=CENTER)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通市值(亿):')
    stockindex_text.insert(tk.INSERT, cy_float_mv)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总股本(亿手):')
    stockindex_text.insert(tk.INSERT, cy_total_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, cy_float_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '自由流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, cy_free_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '换手率:')
    stockindex_text.insert(tk.INSERT, cy_turnover_rate)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市盈率:')
    stockindex_text.insert(tk.INSERT, cy_pe)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市净率:')
    stockindex_text.insert(tk.INSERT, cy_pb)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '收盘点位:')
    stockindex_text.insert(tk.INSERT, cy_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '昨日收盘点:')
    stockindex_text.insert(tk.INSERT, cy_pre_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '涨跌幅(%):')
    stockindex_text.insert(tk.INSERT, cy_pct_chg)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交量(亿手):')
    stockindex_text.insert(tk.INSERT, cy_vol)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交额(亿):')
    stockindex_text.insert(tk.INSERT, cy_amount)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.tag_add('content3', '30.0', 'end')  # 设置选定的内容
    stockindex_text.tag_config('content3', foreground='DarkCyan')

    zx_total_mv = round(shsz_index_dailybasic.at['399005.SZ', 'total_mv'] / 100000000, 2)  # 转换成亿单位
    zx_float_mv = round(shsz_index_dailybasic.at['399005.SZ', 'float_mv'] / 100000000, 2)
    zx_total_share = round(shsz_index_dailybasic.at['399005.SZ', 'total_share'] / 10000000000, 2)  # 转化成亿手
    zx_float_share = round(shsz_index_dailybasic.at['399005.SZ', 'float_share'] / 10000000000, 2)
    zx_free_share = round(shsz_index_dailybasic.at['399005.SZ', 'free_share'] // 10000000000, 2)
    zx_turnover_rate = shsz_index_dailybasic.at['399005.SZ', 'turnover_rate']
    zx_pe = shsz_index_dailybasic.at['399005.SZ', 'pe']
    zx_pb = shsz_index_dailybasic.at['399005.SZ', 'pb']
    zx_close = zx_index_daily.at[0, 'close']
    zx_pre_close = zx_index_daily.at[0, 'pre_close']
    zx_pct_chg = zx_index_daily.at[0, 'pct_chg']
    zx_vol = round(zx_index_daily.at[0, 'vol']/100000000, 2)  # 手转化成亿手
    zx_amount = round(zx_index_daily.at[0, 'amount']/100000, 2)  # 千元转换成亿元

    stockindex_text.insert(tk.INSERT, '中小板指数')
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总市值(亿):')
    stockindex_text.insert(tk.INSERT, zx_total_mv)
    stockindex_text.tag_add('tag4', '43.0', '43.9')  # 设置选定的内容,
    stockindex_text.tag_config('tag4', foreground='red', justify=CENTER)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通市值(亿):')
    stockindex_text.insert(tk.INSERT, zx_float_mv)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '总股本(亿手):')
    stockindex_text.insert(tk.INSERT, zx_total_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, zx_float_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '自由流通股本(亿手):')
    stockindex_text.insert(tk.INSERT, zx_free_share)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '换手率:')
    stockindex_text.insert(tk.INSERT, zx_turnover_rate)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市盈率:')
    stockindex_text.insert(tk.INSERT, zx_pe)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '市净率:')
    stockindex_text.insert(tk.INSERT, zx_pb)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '收盘点位:')
    stockindex_text.insert(tk.INSERT, zx_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '昨日收盘点:')
    stockindex_text.insert(tk.INSERT, zx_pre_close)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '涨跌幅(%):')
    stockindex_text.insert(tk.INSERT, zx_pct_chg)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交量(亿手):')
    stockindex_text.insert(tk.INSERT, zx_vol)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '成交额(亿):')
    stockindex_text.insert(tk.INSERT, zx_amount)
    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.tag_add('content4', '44.0', 'end')  # 设置选定的内容
    stockindex_text.tag_config('content4', foreground='Sienna')

    stockindex_text.insert(tk.INSERT, '\n')
    stockindex_text.insert(tk.INSERT, '数据交易日:')
    stockindex_text.insert(tk.INSERT, strf_time)
    stockindex_text.tag_add('content5', '58.0', 'end')  # 设置选定的内容
    stockindex_text.tag_config('content5', foreground='Crimson')

    stockindex_window = tk.PanedWindow(orient='vertical', opaqueresize=False)
    stockindex_information_window.add(stockindex_window)

    stockindex_sh_frame = tk.Frame(stockindex_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN,
                                   bg='#353535', bd=5, borderwidth=4)
    stockindex_sh_frame.pack(fill=BOTH)
    stockindex_window.add(stockindex_sh_frame, height=screenHeight/2)

    stockindex_sz_frame = tk.Frame(stockindex_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN,
                                   bg='#353535', bd=5, borderwidth=4)
    stockindex_sz_frame.pack(fill=BOTH)
    stockindex_window.add(stockindex_sz_frame)

    for widget_stockindex_sh_frame in stockindex_sh_frame.winfo_children():
        widget_stockindex_sh_frame.destroy()
    for widget_stockindex_sz_frame in stockindex_sz_frame.winfo_children():
        widget_stockindex_sz_frame.destroy()
    for widget_stockindex_text in stockindex_text.winfo_children():
        widget_stockindex_text.destroy()
    # 上证指数
    index_data_sh = pro.index_daily(ts_code='000001.SH', start_date=20100101)
    # 日数据处理
    # :取所有行数据,后面取date列,open列等数据
    index_data_sh = index_data_sh.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
    index_data_sh = index_data_sh.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close',
                                                  'high': 'High', 'low': 'Low', 'vol': 'Volume'})  # 更换列名,为后面函数变量做准备
    index_data_sh.set_index('Date', inplace=True)  # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
    # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
    index_data_sh.index = pd.DatetimeIndex(index_data_sh.index)
    index_data_sh = index_data_sh.sort_index(ascending=True)  # 将时间顺序升序,符合时间序列
    # print(index_data_sh)

    # 设置marketcolors,up:设置K线线柱颜色,up意为收盘价大于等于开盘价,down:与up相反,这样设置与国内K线颜色标准相符
    # edge:K线线柱边缘颜色(i代表继承自up和down的颜色),wick:灯芯(上下影线)颜色,volume:成交量直方图的颜色,inherit:是否继承,选填
    sh_mc = mpf.make_marketcolors(up='red', down='green', edge='i', wick='i', volume='in', inherit=True)
    # 设置图形风格,gridaxis:设置网格线位置,gridstyle:设置网格线线型,y_on_right:设置y轴位置是否在右
    sh_s = mpf.make_mpf_style(gridaxis='both', gridstyle='-.', y_on_right=False, marketcolors=sh_mc)
    # 设置线宽
    mpl.rcParams['lines.linewidth'] = .5
    # 设置均线颜色,这里可以设置6条均线的颜色
    mpl.rcParams['axes.prop_cycle'] = cycler(color=['dodgerblue', 'deeppink', 'navy', 'teal', 'maroon', 'darkorange'])

    index_sh_fig, axlist = mpf.plot(index_data_sh, type='candle', mav=(5, 10, 20), volume=True,
                                    show_nontrading=False, returnfig=True, style=sh_s)

    canvas_index_sh = FigureCanvasTkAgg(index_sh_fig, master=stockindex_sh_frame)  # 设置tkinter绘制区
    canvas_index_sh.draw()
    toolbar_index_sh = NavigationToolbar2Tk(canvas_index_sh, stockindex_sh_frame)
    toolbar_index_sh.update()  # 显示图形导航工具条
    canvas_index_sh._tkcanvas.pack(fill=BOTH, expand=1)

    # 深圳指数
    index_data_sz = pro.index_daily(ts_code='399001.SZ', start_date=20100101)
    # 日数据处理
    # :取所有行数据,后面取date列,open列等数据
    index_data_sz = index_data_sz.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
    index_data_sz = index_data_sz.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close',
                                                  'high': 'High', 'low': 'Low', 'vol': 'Volume'})  # 更换列名,为后面函数变量做准备
    index_data_sz.set_index('Date', inplace=True)  # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
    # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
    index_data_sz.index = pd.DatetimeIndex(index_data_sh.index)
    index_data_sz = index_data_sz.sort_index(ascending=True)  # 将时间顺序升序,符合时间序列
    # print(index_data_sz)

    index_sz_fig, axlist = mpf.plot(index_data_sz, type='candle', mav=(5, 10, 20), volume=True,
                                    show_nontrading=False, returnfig=True)
    canvas_index_sz = FigureCanvasTkAgg(index_sz_fig, master=stockindex_sz_frame)  # 设置tkinter绘制区
    canvas_index_sz.draw()
    toolbar_index_sz = NavigationToolbar2Tk(canvas_index_sz, stockindex_sz_frame)
    toolbar_index_sz.update()  # 显示图形导航工具条
    canvas_index_sz._tkcanvas.pack(fill=BOTH, expand=1)

def stock_query_function():
    # 必须添加以下控件销毁代码,不然点击一次按钮框架长生一次,显示的画面会多一次,你可以将下面的代码删除测试看下
    for widget_graphic_main_frame in graphic_main_frame.winfo_children():
        widget_graphic_main_frame.destroy()
    # 在主框架下创建股票代码输入子框架
    code_frame = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535')
    code_frame.pack()
    # 创建标签‘股票代码’
    stock_label = tk.Label(code_frame, text='股票代码', bd=1)
    stock_label.pack(side=LEFT)
    # 创建股票代码输入框
    input_code_var = tk.StringVar()
    code_widget = tk.Entry(code_frame, textvariable=input_code_var, borderwidth=1, justify=CENTER)
    # input_code_get = input_code_var.set(input_code_var.get())  # 获取输入的新值
    code_widget.pack(side=LEFT, padx=4)

    # 在主框架下创建股票日期输入框子框架
    input_date_frame = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535')
    input_date_frame.pack()
    # 创建标签‘开始日期’
    date_start_label = tk.Label(input_date_frame, text='开始日期', bd=1)
    date_start_label.pack(side=LEFT)
    # 创建开始日期代码输入框
    input_startdate_var = tk.StringVar()
    startdate_widget = tk.Entry(input_date_frame, textvariable=input_startdate_var, borderwidth=1, justify=CENTER)
    input_startdate_get = input_startdate_var.set(input_startdate_var.get())  # 获取输入的新值
    startdate_widget.pack(side=LEFT, padx=4)
    # 创建标签‘结束日期’
    date_end_label = tk.Label(input_date_frame, text='结束日期', bd=1)
    date_end_label.pack(side=LEFT)
    # 创建结束日期代码输入框
    input_enddate_var = tk.StringVar()
    enddate_widget = tk.Entry(input_date_frame, textvariable=input_enddate_var, borderwidth=1, justify=CENTER)
    input_enddate_get = input_enddate_var.set(input_enddate_var.get())  # 获取输入的新值
    enddate_widget.pack(side=LEFT, padx=4)

    # 创建Notebook标签选项卡
    tabControl = ttk.Notebook(graphic_main_frame)
    stock_graphics_daily = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED)  # 增加新选项卡日K线图
    # stock_graphics_daily.pack(expand=1, fill=tk.BOTH, anchor=tk.CENTER)
    stock_graphics_daily_basic = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED)  # 增加新选项卡基本面指标
    stock_graphics_week = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED)
    stock_graphics_month = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED)
    company_information = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED)

    tabControl.add(stock_graphics_daily, text='日K线图')  # 把新选项卡日K线框架增加到Notebook
    tabControl.add(stock_graphics_daily_basic, text='基本面指标')
    tabControl.add(stock_graphics_week, text='周K线图')
    tabControl.add(stock_graphics_month, text='月K线图')
    tabControl.add(company_information, text='公司信息')
    tabControl.pack(expand=1, fill="both")  # 设置选项卡布局
    tabControl.select(stock_graphics_daily)  # 默认选定日K线图开始

    def go():   # 图形输出渲染
        # 以下函数作用是省略输入代码后缀.sz .sh
        def code_name_transform(get_stockcode):  # 输入的数字股票代码转换成字符串股票代码
            str_stockcode = str(get_stockcode)
            str_stockcode = str_stockcode.strip()  # 删除前后空格字符
            if 6 > len(str_stockcode) > 0:
                str_stockcode = str_stockcode.zfill(6) + '.SZ'  # zfill()函数返回指定长度的字符串,原字符串右对齐,前面填充0
            if len(str_stockcode) == 6:
                if str_stockcode[0:1] == '0':
                    str_stockcode = str_stockcode + '.SZ'
                if str_stockcode[0:1] == '3':
                    str_stockcode = str_stockcode + '.SZ'
                if str_stockcode[0:1] == '6':
                    str_stockcode = str_stockcode + '.SH'
            return str_stockcode

        # 清除stock_graphics_daily框架中的控件内容,winfo_children()返回的项是一个小部件列表,
        # 以下代码作用是为每次点击查询按钮时更新图表内容,如果没有以下代码句,则每次点击查询会再生成一个图表
        for widget_daily in stock_graphics_daily.winfo_children():
            widget_daily.destroy()
        for widget_daily_basic in stock_graphics_daily_basic.winfo_children():
            widget_daily_basic.destroy()
        for widget_week in stock_graphics_week.winfo_children():
            widget_week.destroy()
        for widget_month in stock_graphics_month.winfo_children():
            widget_month.destroy()
        for widget_company_information in company_information.winfo_children():
            widget_company_information.destroy()

        # 获取用户输入信息
        stock_name = input_code_var.get()
        code_name = code_name_transform(stock_name)
        start_date = input_startdate_var.get()
        end_date = input_enddate_var.get()

        # 获取股票数据
        stock_data = pro.daily(ts_code=code_name, start_date=start_date, end_date=end_date)
        stock_daily_basic = pro.daily_basic(ts_code=code_name, start_date=start_date, end_date=end_date,
                                            fields='close,trade_date,turnover_rate,volume_ratio,pe,pb')
        stock_week_data = pro.weekly(ts_code=code_name, start_date=start_date, end_date=end_date)
        stock_month_data = pro.monthly(ts_code=code_name, start_date=start_date, end_date=end_date)
        stock_name_change = pro.namechange(ts_code=code_name, fields='ts_code,name')
        stock_information = pro.stock_company(ts_code=code_name, fields='introduction,main_business,business_scope')

        # 日数据处理
        data = stock_data.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]  # :取所有行数据,后面取date列,open列等数据
        data = data.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close', 'high': 'High', 'low': 'Low',
                                    'vol': 'Volume'})  # 更换列名,为后面函数变量做准备
        data.set_index('Date', inplace=True)  # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
        # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
        data.index = pd.DatetimeIndex(data.index)
        data = data.sort_index(ascending=True)  # 将时间顺序升序,符合时间序列

        # 基本面指标数据处理
        stock_daily_basic.set_index('trade_date', inplace=True)  # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
        # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
        stock_daily_basic.index = pd.DatetimeIndex(stock_daily_basic.index)
        stock_daily_basic = stock_daily_basic.sort_index(ascending=True)  # 将时间顺序升序,符合时间序列
        print(stock_daily_basic)

        # 周数据处理
        week_data = stock_week_data.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
        week_data = week_data.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close', 'high': 'High',
                                              'low': 'Low', 'vol': 'Volume'})  # 更换列名,为后面函数变量做准备
        week_data.set_index('Date', inplace=True)  # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
        # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
        week_data.index = pd.DatetimeIndex(week_data.index)
        week_data = week_data.sort_index(ascending=True)  # 将时间顺序升序,符合时间序列

        # 月数据处理
        month_data = stock_month_data.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
        month_data = month_data.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close', 'high': 'High',
                                                'low': 'Low', 'vol': 'Volume'})  # 更换列名,为后面函数变量做准备
        month_data.set_index('Date', inplace=True)  # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
        # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
        month_data.index = pd.DatetimeIndex(month_data.index)
        month_data = month_data.sort_index(ascending=True)  # 将时间顺序升序,符合时间序列

        # 公司信息处理
        stock_company_code = stock_name_change.at[0, 'ts_code']
        stock_company_name = stock_name_change.at[0, 'name']
        stock_introduction = stock_information.at[0, 'introduction']
        stock_main_business = stock_information.at[0, 'main_business']
        stock_business_scope = stock_information.at[0, 'business_scope']

        # K线图图形输出
        daily_fig, axlist = mpf.plot(data, type='candle', mav=(5, 10, 20), volume=True,
                                     show_nontrading=False, returnfig=True)
        # 基本面指标图形输出
        # 注意必须按照选项卡的排列顺序渲染图形输出,假如你把matplotlib的图形放到最后,则会出现图像错位现象,不信你可以把以下的代码放到month_fig后试下
        plt_stock_daily_basic = plt.figure(facecolor='white')
        plt.suptitle('Daily Basic Indicator', size=10)

        fig_close = plt.subplot2grid((3, 2), (0, 0), colspan=2)  # 创建网格子绘图,按行切分成3份,列切分成2分,位置(0,0),横向占用2列
        fig_close.set_title('Close Price')
        plt.xticks(stock_daily_basic.index, rotation=45)  # 设置x轴时间显示方向,放在这跟放在最后显示效果不一样
        fig_close.plot(stock_daily_basic.index, stock_daily_basic['close'])
        plt.xlabel('Trade Day')
        plt.ylabel('Close')
        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))  # 设置X轴主刻度显示的格式
        plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=1))  # 设置X轴主刻度的间距

        fig_turnover_rate = plt.subplot2grid((3, 2), (1, 0))  # 创建网格子绘图,按行切分成3份,列切分成2分,位置(1,0)
        fig_turnover_rate.set_title('Turnover Rate')
        plt.xticks(stock_daily_basic.index, rotation=45)  # 设置x轴时间显示方向,放在这跟放在最后显示效果不一样
        fig_turnover_rate.bar(stock_daily_basic.index, stock_daily_basic['turnover_rate'], facecolor='red')
        plt.xlabel('Trade Day')
        plt.ylabel('Turnover Rate')
        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))  # 设置X轴主刻度显示的格式
        plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2))  # 设置X轴主刻度的间距

        fig_volume_ratio = plt.subplot2grid((3, 2), (2, 0))  # 创建网格子绘图,按行切分成3份,列切分成2分,位置(1,2)
        fig_volume_ratio.set_title('Volume Ratio')
        plt.xticks(stock_daily_basic.index, rotation=45)  # 设置x轴时间显示方向,放在这跟放在最后显示效果不一样
        fig_volume_ratio.bar(stock_daily_basic.index, stock_daily_basic['volume_ratio'])
        plt.xlabel('Trade Day')
        plt.ylabel('Volume Ratio')
        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m'))  # 设置X轴主刻度显示的格式
        plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2))  # 设置X轴主刻度的间距

    由于超出字数限制  完整代码点上面的蓝色字体获取
Copy the code
! [](https://p1-tt-ipv6.byteimg.com/origin/pgc-image/093ef862433249e6b2b38c817a1e7701)
! [](https://p9-tt-ipv6.byteimg.com/origin/pgc-image/60bfdcba9733443d989f9ab17e2c7731)

Tushare registration LINK: LINK