我正在使用Kivy示例代码从两个不同的文件中获取文件路径。 我的目标是使用文件路径打开和操作文件中的数据。
我的问题是将文件路径传递给下面测试函数中的open file命令。
这是我的代码:
from kivy.app import App
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
import re
import pandas as pd
class DropFile(Button):
def __init__(self, **kwargs):
super(DropFile, self).__init__(**kwargs)
# get app instance to add function from widget
app = App.get_running_app()
# add function to the list
app.drops.append(self.on_dropfile)
def on_dropfile(self, widget, path):
# a function catching a dropped file
# if it's dropped in the widget's area
if self.collide_point(*Window.mouse_pos):
self.text = path
def test(self):
minimum_wage = open(**FILE PATH HERE**)
LinesToString = ''
for line in minimum_wage:
LinesToString += line
patFinder = re.compile('\d{5}\s+\d{5,9}')
findPat = re.findall(patFinder, LinesToString)
empno_list = []
pattern = '(\d{5})\s+(\d{5})'
for string in findPat:
match = re.search(pattern, string)
empno = match.group(2)
empno_list.append(empno)
MinimumWage = pd.DataFrame({'EMPNO': empno_list})
MinimumWage.set_index('EMPNO')
print MinimumWage.head()
print MinimumWage.shape
class DropApp(App):
def build(self):
# set an empty list that will be later populated
# with functions from widgets themselves
self.drops = []
# bind handling function to 'on_dropfile'
Window.bind(on_dropfile=self.handledrops)
box = BoxLayout(orientation='vertical')
top_label = Label(text='Data manipulation', font_size=45)
box.add_widget(top_label)
run_button = Button(text='Run', size_hint=(1, 0.5))
run_button.bind(on_press=DropFile.test)
box.add_widget(run_button)
two_buttons = BoxLayout(orientation='horizontal')
dropleft = DropFile(text='Drag & Drop File here')
# dropright = DropFile(text='right')
two_buttons.add_widget(dropleft)
# two_buttons.add_widget(dropright)
box.add_widget(two_buttons)
return box
def handledrops(self, *args):
# this will execute each function from list with arguments from
# Window.on_dropfile
#
# make sure `Window.on_dropfile` works on your system first,
# otherwise the example won't work at all
for func in self.drops:
func(*args)
DropApp().run()
由于
答案 0 :(得分:0)
您可以在test()
的最后一行调用on_dropfile()
方法,例如:
def on_dropfile(self, widget, path):
# a function catching a dropped file
# if it's dropped in the widget's area
if self.collide_point(*Window.mouse_pos):
self.text = path
self.test(path)
def test(self, path):
minimum_wage = open(path)
LinesToString = ''
...
或已从现有物品中发射,例如如果您与test()
函数分开运行on_dropfile()
,并且在更改文本后您不会更改self.text
属性:
def on_dropfile(self, widget, path):
# a function catching a dropped file
# if it's dropped in the widget's area
if self.collide_point(*Window.mouse_pos):
self.text = path # path is assigned to self.text <--
def test(self):
minimum_wage = open(self.text) # <-- and you can use it
LinesToString = ''
...
或者在on_dropfile
结尾处将其放入单独的变量中并在open()
中使用它。