我正在尝试用Kivy开发一个玩具应用程序。
到目前为止,我有一个9 x 9 TextInput
小部件的网格,这些小部件已经以编程方式添加到GridLayout
(我通过id" grid"在我的kv中引用它文件)。
出于某种原因,虽然我为每个TextInput
窗口小部件分配了一个ID,但我在the get_widget_from_id
中获得的ID字典为空。
我错过了什么?
main.py
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.clock import Clock
class SudokuGame(Widget):
# Initialize the grid of text inputs
def __init__(self, **kwargs):
super().__init__(**kwargs)
grid = self.ids["grid"]
for i in range(81):
row = i // 9
col = i % 9
grid.add_widget(TextInput(id = str(row) + "-" + str(col)))
# Try to retrieve one of the widgets from its id
def get_widget_from_id(self, *args):
print(self.ids["grid"].ids)
class SudokuApp(App):
def build(self):
game = SudokuGame()
Clock.schedule_once(game.get_widget_from_id)
return game
if __name__ == '__main__':
SudokuApp().run()
sudoku.kv
#:kivy 1.9.1
<TextInput@SudokuGame>:
text: ""
font_size: 0.7 * self.width
padding: 0.3 * self.width, (self.height - self.line_height) / 2
input_filter: lambda text, from_undo: text if ( 0 < int(text) < 10 and len(self.text) == 0 ) else ""
multiline: False
cursor_color: [0, 0, 0, 0]
<SudokuGame>:
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: "vertical"
size: root.size
GridLayout:
id: grid
rows: 9
cols: 9
line_size: 6
canvas:
Color:
rgb: 0, 0, 0
Rectangle:
pos: self.x + self.width / 3 - self.line_size / 2, self.y
size: self.line_size, self.height
Rectangle:
pos: self.x + 2 * self.width / 3 - self.line_size / 2, self.y
size: self.line_size, self.height
Rectangle:
pos: self.x, self.y + self.height / 3 - self.line_size / 2
size: self.width, self.line_size
Rectangle:
pos: self.x, self.y + 2 * self.height / 3 - self.line_size / 2
size: self.width, self.line_size
BoxLayout:
orientation: "horizontal"
size_hint: 1, 0.1
Button:
text: "Solve"
Button:
text: "Clear"
答案 0 :(得分:1)
ids dict仅由kv ID填充。小工具所具有的Kivy属性实际上是无关的,我不确定它是否用于任何事情。
答案 1 :(得分:0)
坚持这一点可能会解决你的问题
self.ids = {child.id:child for child in self.children}
答案 2 :(得分:0)
杜伦(Lawrence DU)的答案没有解决我的问题,但使我的齿轮旋转。 这个凌乱的代码解决了我的问题,请在您的情况下对其进行测试:
def update_ids(self, **kw):
def recursion(node, parent):
parent.ids = {**parent.ids, **node.ids}
if node.id:
parent.ids[node.id] = node
if node.children:
for child in node.children:
parent.ids = {**parent.ids, **child.ids}
recursion(child, parent)
else:
pass
for c in self.children:
recursion(c, self)