Python学习笔记(4)Drawing on Canvas
原创 2014年04月17日 09:00:25
下面的笔记内容来自coursera上的Python公开课。
in CodeSkulptor, we're going to register the draw handler using a simpleGUI command that we’ll learn. And then, once we've registered it, CodeSkulptor calls the draw handler at around 60 times per second.
1 What does this draw handler do?
What the draw handler does, is the draw handler then updates the canvas, cause all of our drawings going to take place in CodeSkulptor, using a collection of draw commands. That include things like draw_text or draw_line, or something like draw_circle.
例1.1 first example of drawing on the canvas
画图效果如下
# standard HMTL color such as "Red" and "Green" # note later drawing operations overwrite earlier drawing operations import simplegui # Handler to draw on canvas def draw(canvas): canvas.draw_circle([100, 100], 50, 2, "Red", "Pink") canvas.draw_circle([300, 300], 50, 2, "Red", "Pink") canvas.draw_line([100, 100],[300, 300], 2, "Black") canvas.draw_circle([100, 300], 50, 2, "Green", "Lime") canvas.draw_circle([300, 100], 50, 2, "Green", "Lime") canvas.draw_line([100, 300],[300, 100], 2, "Black") canvas.draw_polygon([[150, 150], [250, 150], [250, 250], [150, 250]], 2, "Blue", "Aqua") canvas.draw_text("An example of drawing", [60, 385], 24, "Black") # Create a frame and assign callbacks to event handlers frame = simplegui.create_frame("Home", 400, 400) frame.set_draw_handler(draw) frame.set_canvas_background("Yellow") # Start the frame animation frame.start()
画图效果如下
2 string manipulation
例2.1 Handle single quantity
def convert_units(val, name): result = str(val) + " " + name if val > 1: result = result + "s" return result # convert xx.yy to xx dollars and yy cents def convert(val): # Split into dollars and cents dollars = int(val) cents = int(round(100 * (val - dollars))) # Convert to strings dollars_string = convert_units(dollars, "dollar") cents_string = convert_units(cents, "cent") # return composite string if dollars == 0 and cents == 0: return "Broke!" elif dollars == 0: return cents_string elif cents == 0: return dollars_string else: return dollars_string + " and " + cents_string# 测试用例如下
#测试结果如下
11 dollars and 23 cents
11 dollars and 20 cents
1 dollar and 12 cents
12 dollars and 1 cent
1 dollar and 1 cent
1 cent
1 dollar
注意
其实这行 " cents = int(round(100 * (val - dollars))) "很诡异。如果去掉round写为 cents = int(100 * (val - dollars)),那么print convert(11.20)将返回11 dollars and 19 cents.
例2.2 现在把这个string的输出内容表达在canvas上面
1 上面的例子可以看出,
如果,global variable打印在了canvas上,并且global variable 发生了变化,
那么,global variable的变化也将自动显示在canvas上。
2 draw(canvas)中的从天而降的参数canvas其实是一种语法规定。
The handler should be defined with one parameter, as in the above example. This parameter will receive acanvas object.
类似的用法是input_field输入框
def input_handler(text_input): … frame = simplegui.create_frame('Testing', 100, 100) inp = frame.add_input('My label', input_handler, 50)
阅读全文
Tkinter教程之Canvas篇(1)