我正在尝试通过 ttk.spinbox 显示带有熊猫和 FigureCanvasTkAgg 的图表。
我的代码看起来像无限增加或减少事件。所以如果我点击事件按钮,spinbox 的值会增加(或decr)直到它的范围结束。
但有时它可以按我的意愿工作,即使我对此一无所知
这是什么问题?有什么想法可以暂时限制获得事件吗?我试图给出一个术语来获得下一个事件,但它只是等待一个术语并且无限地工作..
from tkinter import *
import tkinter.ttk as ttk
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class Data:
def __init__(self, data):
self.__data = data
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
root = Tk()
frame_spinbox = Frame(root)
frame_spinbox.pack()
frame_fig = Frame(root)
frame_fig.pack()
spinbox = ttk.Spinbox(frame_spinbox, from_=-10, to=10, validate='key')
spinbox.pack()
data_index = Data(1)
spinbox.set(data_index.data)
figure = plt.Figure(figsize=(5,4), dpi=100)
ax = figure.add_subplot(111)
line = FigureCanvasTkAgg(figure, frame_fig)
line.get_tk_widget().pack(side="left", fill="both")
data = {1 : {"a1" : 11,
"b1" : 12,
"c1" : 13},
2 : {"a2" : 21,
"b2" : 22,
"c2" : 23},
3 : {"a3" : 31,
"b3" : 32,
"c3" : 33}}
def sb_Incr(event, data_index):
print("sb_Incr")
data_index.data += 1
return
def sb_Decr(event, data_index):
print("sb_Decr")
data_index.data -= 1
return
def cmd_Update(ax, figure, data, data_index, sb):
print("cmd_Update")
print("data_index :", data_index.data)
sb.set(data_index.data)
try:
selected_data = data[data_index.data]
except:
print("key Error Occured")
return
df = pd.DataFrame(selected_data, index=[0]).T
print(df)
if df.empty:
print("Empy_DataFrame------")
return
ax.clear()
ax.bar(x=df.index, height=df[0], width=.5, label=df[0])
figure.canvas.draw()
figure.canvas.flush_events()
return
cmd_Update(ax, figure, data, data_index, spinbox)
spinbox.bind("<<Increment>>", lambda x, y=data_index : sb_Incr(x, y))
spinbox.bind("<<Decrement>>", lambda x, y=data_index : sb_Decr(x, y))
spinbox.config(command=lambda w=ax, x=figure, y=data, z=data_index : cmd_Update(w,x,y,z, spinbox))
root.mainloop()