在下面的代码中,根据标题有问题(1)和(2)。
如果按照代码中的描述使用kvLang,则会将图形(蓝色椭圆)绘制到预期的单元格位置(@(1,1) =左上角)。(但是,此时不显示由text:指定的字符串。请告诉我如何显示文本字符....问题(1)
我打算编写一个Python脚本来绘制遵循kvLang的.add_widget方法。
在此脚本中,黄色椭圆出现在右下角,而不是预期的单元格位置((2,2) =>左下角) ...问题(2)
为此,有必要使用.add_widget方法向Grid Laytout添加一个小部件,以便在画布中绘制的形状可以在单元格中显示。
请告诉我们如何解决这个问题。
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Ellipse
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.app import App
Builder.load_string('''
<MyGridLayout@GridLayout>:
cols: 2
Label:
text:"From Kv_1" #(1)Not show. What's problem?
canvas:
Color:
rgb:0,0,1
Ellipse:
pos:self.pos
size:self.size
''')
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_widget(Button(text="From_Py_1"))
self.add_widget(Button(text="From_Py_2"))
labl = Button(text="From_Py_canvas_1")
self.add_widget(labl)
with labl.canvas:
# (2) Expected to draw at cell(2,2) which is same locaton as the lable of "From_Py_canvas_1" but not.
Color(rgb=(1, 1, 0))
Ellipse(pos=labl.pos, size_hint=labl.size_hint)
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()发布于 2019-08-25 12:02:05
问题1:您只需要在kv中使用canvas.before:而不是canvas:。这将在文本之前绘制椭圆,而不是在文本之后(模糊文本)。
问题2:您的Ellipse正在使用labl的当前属性,这些属性在应用程序显示之前都是默认值。要解决此问题,请在之后使用Clock.schedule_once()创建Ellipse。在下面修改的代码中,我保存了对labl的引用,以便在draw_yellow_ellipse()方法中访问它:
from kivy.clock import Clock
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Ellipse
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.app import App
Builder.load_string('''
<MyGridLayout@GridLayout>:
cols: 2
Label:
text:"From Kv_1" #(1)Not show. What's problem?
canvas.before:
Color:
rgb:0,0,1
Ellipse:
pos:self.pos
size:self.size
''')
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_widget(Button(text="From_Py_1"))
self.add_widget(Button(text="From_Py_2"))
self.labl = Button(text="From_Py_canvas_1")
self.add_widget(self.labl)
Clock.schedule_once(self.draw_yellow_ellipse)
def draw_yellow_ellipse(self, dt):
with self.labl.canvas:
# (2) Expected to draw at cell(2,2) which is same locaton as the lable of "From_Py_canvas_1" but not.
Color(rgb=(1, 1, 0))
Ellipse(pos=self.labl.pos, size_hint=self.labl.size_hint)
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()另外,我不认为Ellipse是对size_hint的尊重。也许你是想用size=self.labl.size。如果你这样做,你将再次有一个模糊的Ellipse,在这个例子中,就是你的Button。
https://stackoverflow.com/questions/57642794
复制相似问题