我有两个方法,get_image_one()打开Tkinter文件选择器并返回一个显示在kv文件中的图像。我希望将所选图像设置为check_for_image()方法中的源,以便可以通过check_for_image()对所选图像进行进一步处理,例如检查用户所选图像是否有任何文本等。此测试的逻辑将由check_for_image()提供
请告诉我这是否是最好的方法,即有两个独立的方法,一个用于选择文件,另一个用于验证文件。谢谢你的时间和关注。
下面是我的完整例子。
Me.Py
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from tkinter.filedialog import askopenfilename
from tkinter import Tk
class SampBoxLayout(BoxLayout):
def get_image_one(self):
'''This method is called by button FileChooser, it opens a FileChooser selects the desired image'''
Tk().withdraw()
img1 = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
self.first_image.source = img1
def check_for_image(self):
'''This method is called by button TextIdentifier
1. It needs to get the image selected by the above FileChooser
2. The selected Image can be analysed further Ex: to check the if the selected image contains any text etc.
'''
pass
class SampleApp(App):
def build(self):
# Set the background color for the window
Window.clearcolor = (1, 1, 1, 1)
return SampBoxLayout()
sample_app = SampleApp()
sample_app.run()
样品千伏
#:kivy 1.10.0
<ColoredBackground@Image>:
font_size: '48sp'
color: (.9, .5, .4, 1)
canvas.before:
Color:
rgb: (.2, .9, .9)
Rectangle:
pos: self.x + sp(2), self.y + sp(2)
size: self.width - sp(5), self.height - sp(4)
<SampBoxLayout>:
first_image: first_image # <----
orientation: "vertical"
padding: 10
spacing: 10
# ---------- Button FileChooser ----------
BoxLayout:
orientation: "horizontal"
height: 30
Button:
text: "FileChooser"
on_press: root.get_image_one()
Button:
text: "TextIdentifier"
on_press: root.check_for_image()
# ---------- Display Images----------
BoxLayout:
orientation: "vertical"
height: 30
ColoredBackground:
id: first_image # <----
size: self.parent.width, self.parent.height
allow_stretch: True
keep_ratio: False