我有一串文字如下:
1x2xx1x2xx1x2xx1x2xxx
我需要拆开文本字符串,如果它是一个数字,我想将该数字与一些其他变量一起传递给另一个函数,以在画布上打印方块。
我写了以下代码:
def process_single_line(a_canvas, line_of_pattern, left, top, size):
x = left
y = top
for char in line_of_pattern:
if char.isdigit():
type_of_tile = int(char)
draw_tile (a_canvas, type_of_tile, x, y, size)
else:
x += size
我遇到的问题是:
答案 0 :(得分:2)
我相信你应该在渲染后总是递增x位置。
试试这个:
def process_single_line(a_canvas, line_of_pattern, left, top, size):
x = left
y = top
for char in line_of_pattern:
if char.isdigit():
type_of_tile = int(char)
draw_tile (a_canvas, type_of_tile, x, y, size)
x += size
答案 1 :(得分:2)
多行解决方案(如果您没有)
def process_single_line(a_canvas, line_of_pattern, left, top, size):
x = left
y = top
for char in line_of_pattern:
if char.isdigit():
type_of_tile = int(char)
draw_tile(a_canvas, type_of_tile, x, y, size)
x += size
lines = ['1x2xx1x2xx1x2xx1x2xxx', '3xxxx3xxxx3xxxx3xxxx']
for line_num, line in enumerate(lines):
process_single_line(canvas, line, 0, size*line_num, size)