我想通过在textinput中输入多个bin来更新我的直方图的bin。在文本框中输入值后,应在单击按钮后更新直方图。
我的代码如下:
import matplotlib
matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
from kivy.app import App
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas, NavigationToolbar2Kivy
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
import matplotlib.pyplot as plt
import csv
with open("c:/Users/Niels/Desktop/uranite_23_03_2017.csv", 'rb') as f:
reader = csv.reader(f, delimiter=';')
data = []
for column in reader:
data.append(column[1])
results = data
results = [int(i) for i in results]
bins = 200
plt.hist(results, bins=bins)
plt.title("Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
fig = plt.gcf()
canvas = fig.canvas
def callback(self):
global fig, results
#bins = 50
plt.hist(results,bins=bins)
canvas.draw()
class HistogramApp(App):
title = 'Histogram data'
def build(self):
fl = BoxLayout(orientation="vertical")
self.btn1 = Button(text="Update", height=40, size_hint_y=None)
self.btn1.bind(on_press=callback)
self.tekstvak = TextInput(height=30, size_hint_y=None, multiline=False)
nav1 = NavigationToolbar2Kivy(canvas)
fl.add_widget(nav1.actionbar)
fl.add_widget(canvas)
fl.add_widget(self.tekstvak)
fl.add_widget(self.btn1)
return fl
if __name__ == '__main__':
HistogramApp().run().
回调函数运行正常。如果我在此功能中手动输入分档,则直方图将按照应有的方式更新。但是如何通过在textinput中输入数字来实现呢?
答案 0 :(得分:0)
您需要定义callback
以便它接收二进制数作为参数,然后在将on_press
事件绑定到按钮时提供TextInput文本属性。首先,callback
# Callback takes one argument that is the number of bins
def callback(bins):
global fig, results
# Clear the plot figure, otherwise you'll end up with multiple plots overlayed
plt.clf()
# Convert bins to integer. You may want to use try/except statements to check if bins is convertable to integer and, if not, handle the exception
bins = int(bins)
plt.hist(results,bins=bins)
canvas.draw()
现在是HistogramApp:
class HistogramApp(App):
title = 'Histogram data'
def build(self):
fl = BoxLayout(orientation="vertical")
self.btn1 = Button(text="Update", height=40, size_hint_y=None)
self.tekstvak = TextInput(height=30, size_hint_y=None, multiline=False)
# Bind the on press event after defining self.tekstvak
# Note the use of lambda so that we can provide our own
# argument to the callback. The argument is simply the
# reference to the TextInput instance text property
self.btn1.bind(on_press=lambda x: callback(self.tekstvak.text))
nav1 = NavigationToolbar2Kivy(canvas)
fl.add_widget(nav1.actionbar)
fl.add_widget(canvas)
fl.add_widget(self.tekstvak)
fl.add_widget(self.btn1)
return fl
您甚至可以将相同的回调绑定到TextInput的on_text_validate
事件。通过这种方式,您可以输入垃圾箱数量,按Enter键就可以了。
self.tekstvak.bind(on_text_validate=lambda x: callback(self.tekstvak.text))