尝试创建网站" Leafly"的基本版本。我希望使用用户输入在数据集中查找一行,并在用户输入的内容上显示所有信息。
我将用户的文本输入保存到TXT文件,然后在下一个窗口中打开文本文件。TXT文件可以保存良好,但由于某种原因,它仅在我关闭应用程序后才加载正确的文本。 因此,如果用户将文本输入到InputText框中,它将保存到TXT文件中,但是当我尝试在下一个窗口中显示该TXT文件时,它只会在加载程序之前加载文本文件。如果我再次运行该程序,则以前的用户输入有效,但我希望它能在不必关闭应用程序的情况下进行。
我是Python的新手,因此可以解释您看到的任何怪异代码。我正在使用的数据集可以在此处找到:https://www.kaggle.com/kingburrito666/cannabis-strains
我也知道这是多么有趣和荒谬,这是哈哈,但是如果您能帮助您,我会欣赏它!
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
import pandas as pd
from kivy.properties import StringProperty
from pathlib import Path
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
df = pd.read_csv("cannabis.csv", sep=",")
class Menu(Screen):
pass
class MainWindow(Screen):
pass
class SecondWindow(Screen):
st = str("")
str(df[df['Strain'].str.match(st)])
type = ObjectProperty(None)
def btn(self):
self.st = self.st + str(self.type.text)
self.st = str(self.st)
print(self.st, file=open("text.txt", "w"))
然后
class ThirdWindow(Screen):
with open('text.txt', 'r') as myfile:
data = myfile.read().strip()
strain = StringProperty(str(df[df['Strain'].str.match(str(data))]))
class WindowManager(ScreenManager):
pass
kv = Builder.load_file("my.kv")
class MyMainApp(App):
def build(self):
return kv
if __name__== "__main__":
MyMainApp().run()
.kv文件
WindowManager:
Menu
MainWindow:
SecondWindow:
ThirdWindow:
<Menu>:
name: "menu"
GridLayout:
cols:1
Button:
text: "Launch My Weed"
on_release:
app.root.current = "main"
然后
<MainWindow>:
name: "main"
GridLayout:
cols:1
GridLayout:
cols:2
Label:
text: "Password: "
TextInput:
id: password
multiline: False
Button:
text: "Login"
on_release:
app.root.current = "second" if password.text == "password" else "main"
root.manager.transition.direction = "left"
然后
<SecondWindow>:
name: "second"
type: type
GridLayout:
cols:1
GridLayout:
cols:2
Label:
text: "Strain?: "
TextInput:
id: type
multiline: False
Button:
text: "Tell Me About My Weed"
on_release:
app.root.current = "third"
root.manager.transition.direction = "down"
root.btn()
<ThirdWindow>:
name: "third"
GridLayout:
cols:1
GridLayout:
cols:2
Label:
text : root.strain
您读取ThirdWindow
的类定义中的文本文件,如果您希望在输入屏幕时发生,则可以将此代码放在on_pre_enter
(或on_enter
(中但这将在过渡完成后发生,因此,如果它更改内容,它可能会"闪烁"(。
class ThirdWindow(Screen):
strain = StringProperty()
def on_pre_enter(self, *args):
with open('text.txt', 'r') as myfile:
data = myfile.read().strip()
self.strain = str(df[df['Strain'].str.match(str(data))])