我是Kivy和GUI的新手,很难理解Kivy回调逻辑的一些简单概念。我想制作一个简单的应用程序来读取CSV并从中绘制图形,所以我希望打开文件的小部件触发一个函数,该函数添加一个显示图形的FigureCanvaKivyAgg小部件。
在我的源代码中,我禁用了从CSV读取的绘图,因为它不会增加手头的问题。你会看到,我尝试了不同的方式来触发回调,但我只完成了触发自定义事件,它没有与回调通信,也没有将FigureCanva Widget添加到布局中。
import pandas as pd
import matplotlib.pyplot as plt
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserIconView
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from shark_plot import shark_plot
import os
csv = {'x':[1,2,3,4,5,6],'y':[2,4,6,8,6,12]}
class MyWidget(BoxLayout):
def __init__(self, **kwargs):
super(MyWidget, self).__init__(**kwargs)
self.register_event_type('on_event')
container = BoxLayout(orientation='vertical')
filechooser = FileChooserIconView()
filechooser.bind(on_selection=lambda x: self.selected(filechooser.selection))
print(filechooser.selection,filechooser.path)
open_btn = Button(text='open', size_hint=(1, .2))
open_btn.bind(on_release=lambda x: self.open(filechooser.path, filechooser.selection))
box = BoxLayout(size_hint=(1, .5))
box.bind(on_event= self.action)
# if len(filechooser.path[0])>0:
# # box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
container.add_widget(filechooser)
container.add_widget(open_btn)
container.add_widget(box)
self.add_widget(container)
def on_event(self):
print("Event triggered?")
plt.show()
canva = (FigureCanvasKivyAgg(plt.gcf()))
return canva
def action(self):
print('Action executed??')
canva = (FigureCanvasKivyAgg(plt.gcf()))
self.cb.ask_update()
return canva
def open(self, path, filename):
print(filename)
if len(filename) > 0:
selected_path = os.path.join(path, filename[0])
print(selected_path)
df=pd.read_csv(selected_path)
# fig = shark_plot(df)
fig = plt.plot(csv['x'],csv['y'])
g=self.dispatch('on_event')
print(type(df))
# print(f.read())
return fig
def selected(self, filename):
print("selected: %s" % filename[0])
def on_event_callback():
print("Action Triggered??")
canva = (FigureCanvasKivyAgg(plt.gcf()))
subbox = BoxLayout()
subbox.add_widget(canva)
return subbox
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
希望问题清楚,这是我第一次在这里这样做:(
如有任何澄清,请联系。
on_event((将通过dispatch((语句运行,但在on_event_callback((中没有从on_eevent((到add_widget((语句的连接,因此永远不会发生这种情况。您可以将add_widget((直接放在on_event((中,或者,如果您想要一个单独的函数,则直接从open((调用它,而不使用kivy寄存器和dispatch((。
def on_event(self):
canva = FigureCanvasKivyAgg(plt.gcf())
self.add_widget(canva)
def on_event_callback(self,canva):
self.add_widget(canva)
def open(self, path, filename):
# open data files here etc to load self.csv
plt.plot(self.csv['x'],self.csv['y'])
self.dispatch('on_event')
canva2 = FigureCanvasKivyAgg(plt.gcf())
self.on_event_callback(canva2)