圆周率动态画出程序

from random import randint
from turtle import *

points = ([(119, 124), (120, 125), (125, 125), (126, 124), (126, 118), (125, 117), (125, 116), (124, 115), (124, 114), (118, 108), (117, 108), (114, 105), (113, 105), (112, 104), (111, 104), (109, 102), (108, 102), (107, 101), (106, 101), (105, 100), (104, 100), (103, 99), (102, 99), (101, 98), (100, 98), (99, 97), (97, 97), (96, 96), (94, 96), (93, 95), (90, 95), (89, 94), (59, 94), (58, 93), (58, 91), (57, 90), (57, 89), (56, 88), (56, 86), (55, 85), (55, 83), (54, 82), (54, 80), (53, 79), (53, 78), (52, 77), (52, 75), (51, 74), (51, 72), (50, 71), (50, 69), (49, 68), (49, 66), (48, 65), (48, 64), (47, 63), (47, 61), (46, 60), (46, 58), (45, 57), (45, 55), (44, 54), (44, 52), (43, 51), (43, 49), (42, 48), (42, 46), (41, 45), (41, 43), (40, 42), (40, 39), (39, 38), (39, 36), (38, 35), (38, 33), (37, 32), (37, 30), (36, 29), (36, 26), (35, 25), (35, 23), (34, 22), (34, 20), (33, 19), (33, 16), (32, 15), (32, 13), (31, 12), (31, 9), (30, 8), (30, 6), (29, 5), (29, 2), (28, 1), (28, -2), (27, -3), (27, -5), (26, -6), (26, -9), (25, -10), (25, -13), (24, -14), (24, -17), (23, -18), (23, -21), (22, -22), (22, -25), (21, -26), (21, -29), (20, -30), (20, -34), (19, -35), (19, -38), (18, -39), (18, -43), (17, -44), (17, -47), (16, -48), (16, -52), (15, -53), (15, -58), (14, -59), (14, -65), (13, -66), (13, -81), (12, -82), (13, -83), (13, -90), (14, -91), (14, -92), (15, -93), (15, -94), (16, -95), (16, -96), (18, -98), (19, -98), (21, -100), (22, -100), (23, -101), (26, -101), (27, -102), (36, -102), (37, -101), (39, -101), (40, -100), (41, -100), (42, -99), (43, -99), (44, -98), (45, -98), (46, -97), (47, -97), (49, -95), (50, -95), (52, -93), (53, -93), (56, -90), (57, -90), (60, -87), (61, -87), (67, -81), (68, -81), (73, -76), (77, -80), (76, -81), (76, -82), (73, -85), (73, -86), (69, -90), (69, -91), (64, -96), (64, -97), (53, -108), (52, -108), (47, -113), (46, -113), (44, -115), (43, -115), (41, -117), (40, -117), (39, -118), (38, -118), (37, -119), (36, -119), (35, -120), (34, -120), (33, -121), (31, -121), (30, -122), (28, -122), (27, -123), (24, -123), (23, -124), (14, -124), (13, -123), (10, -123), (9, -122), (8, -122), (7, -121), (6, -121), (-1, -114), (-1, -113), (-3, -111), (-3, -110), (-4, -109), (-4, -108), (-5, -107), (-5, -105), (-6, -104), (-6, -102), (-7, -101), (-7, -98), (-8, -97), (-8, -83), (-7, -82), (-7, -76), (-6, -75), (-6, -70), (-5, -69), (-5, -66), (-4, -65), (-4, -62), (-3, -61), (-3, -58), (-2, -57), (-2, -54), (-1, -53), (-1, -51), (0, -50), (0, -47), (1, -46), (1, -44), (2, -43), (2, -41), (3, -40), (3, -38), (4, -37), (4, -35), (5, -34), (5, -32), (6, -31), (6, -29), (7, -28), (7, -26), (8, -25), (8, -23), (9, -22), (9, -20), (10, -19), (10, -17), (11, -16), (11, -14), (12, -13), (12, -11), (13, -10), (13, -8), (14, -7), (14, -5), (15, -4), (15, -2), (16, -1), (16, 1), (17, 2), (17, 4), (18, 5), (18, 7), (19, 8), (19, 10), (20, 11), (20, 13), (21, 14), (21, 16), (22, 17), (22, 19), (23, 20), (23, 22), (24, 23), (24, 25), (25, 26), (25, 28), (26, 29), (26, 31), (27, 32), (27, 34), (28, 35), (28, 37), (29, 38), (29, 40), (30, 41), (30, 43), (31, 44), (31, 46), (32, 47), (32, 49), (33, 50), (33, 52), (34, 53), (34, 55), (35, 56), (35, 58), (36, 59), (36, 61), (37, 62), (37, 64), (38, 65), (38, 67), (39, 68), (39, 70), (40, 71), (40, 73), (41, 74), (41, 76), (42, 77), (42, 79), (43, 80), (43, 82), (44, 83), (44, 85), (45, 86), (45, 88), (46, 89), (46, 91), (47, 92), (47, 94), (-20, 94), (-20, 92), (-21, 91), (-21, 90), (-22, 89), (-22, 87), (-23, 86), (-23, 84), (-24, 83), (-24, 82), (-25, 81), (-25, 79), (-26, 78), (-26, 76), (-27, 75), (-27, 73), (-28, 72), (-28, 71), (-29, 70), (-29, 68), (-30, 67), (-30, 65), (-31, 64), (-31, 62), (-32, 61), (-32, 59), (-33, 58), (-33, 57), (-34, 56), (-34, 54), (-35, 53), (-35, 51), (-36, 50), (-36, 48), (-37, 47), (-37, 45), (-38, 44), (-38, 43), (-39, 42), (-39, 40), (-40, 39), (-40, 37), (-41, 36), (-41, 34), (-42, 33), (-42, 31), (-43, 30), (-43, 28), (-44, 27), (-44, 25), (-45, 24), (-45, 23), (-46, 22), (-46, 20), (-47, 19), (-47, 17), (-48, 16), (-48, 14), (-49, 13), (-49, 11), (-50, 10), (-50, 8), (-51, 7), (-51, 5), (-52, 4), (-52, 2), (-53, 1), (-53, -1), (-54, -2), (-54, -4), (-55, -5), (-55, -7), (-56, -8), (-56, -10), (-57, -11), (-57, -13), (-58, -14), (-58, -16), (-59, -17), (-59, -19), (-60, -20), (-60, -22), (-61, -23), (-61, -25), (-62, -26), (-62, -28), (-63, -29), (-63, -31), (-64, -32), (-64, -34), (-65, -35), (-65, -37), (-66, -38), (-66, -40), (-67, -41), (-67, -43), (-68, -44), (-68, -46), (-69, -47), (-69, -49), (-70, -50), (-70, -53), (-71, -54), (-71, -56), (-72, -57), (-72, -59), (-73, -60), (-73, -62), (-74, -63), (-74, -65), (-75, -66), (-75, -68), (-76, -69), (-76, -72), (-77, -73), (-77, -75), (-78, -76), (-78, -78), (-79, -79), (-79, -81), (-80, -82), (-80, -85), (-81, -86), (-81, -88), (-82, -89), (-82, -91), (-83, -92), (-83, -95), (-84, -96), (-84, -98), (-85, -99), (-85, -101), (-86, -102), (-86, -105), (-87, -106), (-87, -108), (-88, -109), (-88, -111), (-89, -112), (-89, -113), (-91, -115), (-91, -116), (-97, -122), (-98, -122), (-99, -123), (-101, -123), (-102, -124), (-113, -124), (-114, -123), (-117, -123), (-118, -122), (-120, -122), (-121, -121), (-122, -121), (-125, -118), (-125, -117), (-126, -116), (-126, -111), (-125, -110), (-125, -108), (-124, -107), (-124, -105), (-123, -104), (-123, -103), (-122, -102), (-122, -101), (-120, -99), (-120, -98), (-118, -96), (-118, -95), (-116, -93), (-116, -92), (-114, -90), (-114, -89), (-112, -87), (-112, -86), (-110, -84), (-110, -83), (-108, -81), (-108, -80), (-107, -79), (-107, -78), (-105, -76), (-105, -75), (-104, -74), (-104, -73), (-102, -71), (-102, -70), (-101, -69), (-101, -68), (-100, -67), (-100, -66), (-98, -64), (-98, -63), (-97, -62), (-97, -61), (-96, -60), (-96, -59), (-95, -58), (-95, -57), (-94, -56), (-94, -55), (-93, -54), (-93, -53), (-91, -51), (-91, -50), (-90, -49), (-90, -48), (-89, -47), (-89, -46), (-88, -45), (-88, -44), (-87, -43), (-87, -42), (-86, -41), (-86, -40), (-85, -39), (-85, -38), (-84, -37), (-84, -35), (-83, -34), (-83, -33), (-82, -32), (-82, -31), (-81, -30), (-81, -29), (-80, -28), (-80, -27), (-79, -26), (-79, -25), (-78, -24), (-78, -23), (-77, -22), (-77, -20), (-76, -19), (-76, -18), (-75, -17), (-75, -16), (-74, -15), (-74, -14), (-73, -13), (-73, -12), (-72, -11), (-72, -9), (-71, -8), (-71, -7), (-70, -6), (-70, -5), (-69, -4), (-69, -2), (-68, -1), (-68, 0), (-67, 1), (-67, 3), (-66, 4), (-66, 5), (-65, 6), (-65, 8), (-64, 9), (-64, 10), (-63, 11), (-63, 13), (-62, 14), (-62, 15), (-61, 16), (-61, 18), (-60, 19), (-60, 20), (-59, 21), (-59, 23), (-58, 24), (-58, 26), (-57, 27), (-57, 28), (-56, 29), (-56, 31), (-55, 32), (-55, 33), (-54, 34), (-54, 36), (-53, 37), (-53, 38), (-52, 39), (-52, 41), (-51, 42), (-51, 44), (-50, 45), (-50, 46), (-49, 47), (-49, 49), (-48, 50), (-48, 51), (-47, 52), (-47, 54), (-46, 55), (-46, 56), (-45, 57), (-45, 59), (-44, 60), (-44, 62), (-43, 63), (-43, 64), (-42, 65), (-42, 67), (-41, 68), (-41, 69), (-40, 70), (-40, 72), (-39, 73), (-39, 74), (-38, 75), (-38, 77), (-37, 78), (-37, 80), (-36, 81), (-36, 82), (-35, 83), (-35, 85), (-34, 86), (-34, 87), (-33, 88), (-33, 90), (-32, 91), (-32, 93), (-31, 94), (-58, 94), (-59, 93), (-65, 93), (-66, 92), (-70, 92), (-71, 91), (-74, 91), (-75, 90), (-77, 90), (-78, 89), (-80, 89), (-81, 88), (-82, 88), (-83, 87), (-84, 87), (-85, 86), (-86, 86), (-87, 85), (-88, 85), (-89, 84), (-90, 84), (-91, 83), (-92, 83), (-94, 81), (-95, 81), (-97, 79), (-98, 79), (-101, 76), (-102, 76), (-111, 67), (-114, 70), (-114, 72), (-113, 73), (-113, 74), (-112, 75), (-112, 76), (-110, 78), (-110, 79), (-109, 80), (-109, 81), (-108, 82), (-108, 83), (-106, 85), (-106, 86), (-104, 88), (-104, 89), (-101, 92), (-101, 93), (-89, 105), (-88, 105), (-86, 107), (-85, 107), (-84, 108), (-83, 108), (-81, 110), (-79, 110), (-78, 111), (-77, 111), (-76, 112), (-74, 112), (-73, 113), (-71, 113), (-70, 114), (-68, 114), (-67, 115), (-63, 115), (-62, 116), (-57, 116), (-56, 117), (82, 117), (83, 118), (97, 118), (98, 119), (102, 119), (103, 120), (107, 120), (108, 121), (110, 121), (111, 122), (113, 122), (114, 123), (116, 123), (117, 124), (119, 124)],)
screen = Screen()
screen.setup(960,780)
screen.colormode(255)


t = Turtle(shape='turtle')
t.penup()

for poly  in points:
    r = randint(0,255)
    g = randint(0,255)
    b = randint(0,255)
    t.fillcolor(r,g,b)
    t.begin_fill()
    for x,y in poly:
       t.goto(x,y)
       if not t.isdown():t.down()
    t.end_fill()
    t.penup()
t.ht()
screen.mainloop()

发表在 python, turtle | 留下评论

割圆术动画_需要最新sprites版本

import time
import math
import random
import turtle
from sprites import *

def rndcolor():
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    return r,g,b

def draw_polygon(turtle,cors):
    d = math.dist(cors[0],cors[1])
    turtle.penup()
    turtle.goto(cors[0])
    turtle.pendown()
    for x,y in cors[1:]:
        turtle.goto(x,y)
    turtle.goto(cors[0])
    turtle.penup()
    周长 = d * len(cors)
    return 周长

turtle.colormode(255)

screen = Screen()
screen.setup(500,500)
screen.bgcolor('black')
screen.tracer(0,0)

A = (-200,0)
B =(200,0)
pen = Sprite('blank')
pen.width(2)
pen.color('white')
pen.draw_circle(A,B)

ft = ('黑体',16,'normal')
p = Sprite('blank')        # 写圆周率的
p.sety(220)
p.pencolor('yellow')

frames = []
t = Sprite('blank')
for n in range(3,101):
    t.home()
    t.fd(200)
    t.left(90)
    points = []
    for i in range(n):
        t.circle(200,360/n)
        points.append(t.position())
    t.randomcolor()
    周长 = draw_polygon(t,points)
    pi = 周长/400
    p.clear()
    p.write(f'n={n},π={pi}',align='center',font=ft)
    screen.update()
    frames.append(screen.save())
    t.wait(2/n)
    #t.clear()
for index,frame in enumerate(frames):
    frame.save(f'gframes/{index}.png')

screen.mainloop()
    

发表在 python, sprites | 留下评论

本程序返回折线的拐点.py

"""
  本程序返回折线的拐点.py
  这是研究在python turtle中实现bloodfill算法的一个副产品。
  作者:李兴球,2022/12/3号
"""
import random
import turtle

def draw_segments(points):
    turtle.penup()
    turtle.goto(points[0])
    turtle.pendown()
    [turtle.goto(dot) for dot in points[1:] ]
    turtle.penup()
    
def twopointoneline(p1,p2):
    """两点一线函数,
    p1,p2表示坐标点,用二元组表示,本函数根据两点返回一元一次方程一般式的A,B,C,k,b"""
    x1,y1 = p1
    x2,y2 = p2
    dx = x1 - x2
    if dx==0:
        k = b = float('inf')
    else:
        k = (y1-y2)/dx
        b = (x1*y2-x2*y1)/dx
    A = y2 - y1
    B = dx
    C = (x2*y1-x1*y2)
    return A,B,C,k,b
twopaline = twopointoneline    # 两点一线的别名
twodotaline = twopointoneline

def point_is_on_line(point,line):
    """判断点是否在直线上,point:二元组表示的点,line:两个点表示的直线"""
    P,Q = line
    A,B,C,k,b = twopointoneline(P,Q) # 直线方程标准式,k斜率,b截距
    #print("A,B,C,k,b",A,B,C,k,b)
    x,y = point
    #print("x y = ",x,y)
    return abs(A*x + B*y + C)<0.00000001     # 符合直线标准方程则返回真,否则假        
dot_is_on_line = point_is_on_line

def point_is_on_segment(point,segment):
    """判断点是否在线段上,
       point:二元组表示的点,segment:两个点表示的线段,如((10,10),(20,20))或[(0,0),(100,100)]"""
    P,Q = segment    
    x,y = point
    if point_is_on_line(point,segment):   # 如果在直线上,进一步判断是否在线段上
        x1 = P[0];x2 = Q[0] # 线段1的两个x坐标
        if x1>x2:x1,x2 = x2,x1         # 如果x1比x2大,则交换x1和x2的值
        if x>x2 or xy2:y1,y2 = y2,y1         # 如果y1比y2大,则交换y1和y2的值
        if y>y2 or y
							
发表在 python, turtle | 留下评论

点转图像测试程序,本程序是为在python海龟绘图中使用洪水填充而作的一个中间研究程序

"""
 点转图像测试程序,本程序是为在python海龟绘图中使用洪水填充而作的一个中间研究程序,作者李兴球.
"""
import cv2
import turtle
import numpy as np

def convert_turtle_xy(pos,w,h,img_w,img_h):
    """pos是以左上角为原点,向右为正x,向下为正y的坐标,函数把它转换成turtle坐标"""
    x,y = pos
    x = x - img_w//2    
    y = -y+ img_h//2
    return x,y

def points2image(points):
    """坐标点转换为灰图像,x->,y向下为正"""
    min_x = min([x for x,y in points])
    max_x = max([x for x,y in points])
    min_y = min([y for x,y in points])
    max_y = max([y for x,y in points])
    left,top = min_x,min_y
    width = max_x - min_x +1
    height = max_y - min_y +1
    image = [[255 for i in range(width)] for j in range(height)] 
    new_points = [(x-left,y-top) for x,y in points]
    #print('new_points=',new_points)
    #for row in image:
    #    print(row)
    for i in range(height):
        for j in range(width):
            if (j,i) in new_points:
                image[i][j] = 0
    return image

# 这些坐标点是以左上角为原点的,(x向右为正,y轴向下为正)
A = (10,5);B=(10,200);C=(150,150);D=(200,100);E=(300,300);F=(330,330)
ps = [A,B,C,D,E,F]
img = points2image(ps)
gray = np.array(img,dtype='uint8')
print(gray)
img_height,img_width = gray.shape[0:]    # 高度、宽度

ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
print(gray)
# 提取轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


w,h = 800,900
turtle.setup(w,h)
turtle.penup()
turtle.speed(0)
turtle.delay(0)
for item in contours:
   cors = [convert_turtle_xy(tuple(lis[0]),w,h,img_width,img_height) for lis in item]
   cors.append(convert_turtle_xy(tuple(item[0][0]),w,h,img_width,img_height))
   for x,y in cors:
       turtle.goto(x,y);turtle.dot()
       if not turtle.isdown():turtle.down()
   turtle.penup()

发表在 python, turtle | 留下评论

math.floor函数演示程序.py

李兴球Pythonmath.floor函数演示程序.py
这是我们上青少年Python课的一个小例子,要的人拿去用吧。当然,两个for循环合并起来也是完全可以的。请同学们改成用while循环重新实现。

"""
   math.floor函数演示程序.py
   阶梯图形制作演示程序.py
"""
import math
import turtle

turtle.speed(0)
turtle.delay(0)
turtle.bgcolor('black')
turtle.color('magenta')
turtle.penup()
for x in range(-200,200):
    y = 50 * math.floor(x/50)
    turtle.goto(x,y)
    turtle.dot(4)
    
for x in range(-200,200):
    y = -50 * math.floor(x/50)
    turtle.goto(x,y)
    turtle.dot(4)
    
turtle.done()

发表在 python, turtle | 标签为 | 留下评论

单击按钮让小车走的两个小动画

李兴球Python单击按钮小车行驶相对运动
被疫情封在家两个礼拜了,每天有核酸检测人员上门做核酸,这个为什么总要检查,普通病去医院检一次即可。这个小病毒呢,天天要检查是否是阳性。好像总是怀疑检测不对,然后又要重新检测似的。当然不可能无限循环,不过这检测次数也太多了。外国人知道了会认为中国人是世界上最胆小的民族,以后势必成为笑柄。

总之,不看过程,只看结果,那就是我们的社会病了,社会被强行按下暂停键,让每个人思考这是为什么?
是新冠病毒吗?这是表象,显然不是由于新冠病毒。社会的发展有其规律,今年不产生新冠病毒,也会在明年产生新冠病毒,总之这个新冠病毒是一定会产生的,那么它为什么会一定会产生,这背后的逻辑是什么?

我们要通过现象看本质。我看到网上有种说法是,由于科学技术造成地球环境大污染导致生态失衡。
比如,我们地球处于石油农业阶段,即把农业发展建立在以石油、煤和天然气等能源和原料为基础,以高投资、高能耗方式经营的大型农业。这造成土地板结,土地不断退化,地球生态环境被人类破坏,地球正在经历第三次生物大灭绝。

即,现代农业就是反地球演化的。因为地球不需要人类,也能活得更好。今天编了一个程序,演示效果如上所示:
代码如下所示:

import time
import turtle

def movebus(x,y):            # for button1     
    sp = button1.shape()
    if sp!='b1.gif': return  # 如果不造型是b1.gif,是灰色,则单击无效
    button1.shape('b1_disable.gif')
    button2.shape('b2_disable.gif')     
    button1.onclick(None)
    turtle.clear()
    turtle.write('演示中...',align='center',font=('',12,'normal'))
    while bus.xcor()<340:
        bus.fd(10)
        time.sleep(0.01)
    bus.setx(-340)
    button1.onclick(movebus)
    button1.shape('b1.gif')
    button2.shape('b2.gif')
    turtle.clear()
    turtle.write('演示完毕...',align='center',font=('',12,'normal'))     

def movebg(x,y):               # for button2     
    pass

 
turtle.setup(480,360)
turtle.delay(0)
turtle.bgpic('city_960x360.gif')
turtle.title('汽车行驶与相对运动演示动画')
turtle.ht()
turtle.penup()
turtle.speed(0)
turtle.sety(150)
turtle.color('magenta')

sc = turtle.getscreen()
root = sc._root
root.resizable(0,0)          # 关闭缩放

sc.addshape('b1.gif')        # 添加造型
sc.addshape('b2.gif')
sc.addshape('b1_disable.gif')
sc.addshape('b2_disable.gif')
sc.addshape('bus.gif')
cv = turtle.getcanvas()      # 获取画布

bus = turtle.Turtle('bus.gif')
bus.penup()
bus.speed(0)
bus.goto(-340,-100)

button1 = turtle.Turtle('b1.gif')
button1.penup()
button1.speed(0)
button1.bk(100)
button1.onclick(movebus)    # 绑定事件

button2 = turtle.Turtle('b2_disable.gif')
button2.penup()
button2.speed(0)
button2.fd(100)
button2.onclick(movebg)

sc.mainloop()
 

发表在 python, turtle | 留下评论

单击格子填充随机颜色正方形演示的练习题

李兴球Python单击填充演示
请同学们完成如图所示功能,把下面代码完善即可:

import random
import turtle

def fill_square(x,y):
    """x,y是小正方形内随机的一个坐标,如果刚好在左边上,则填充右边的小正方形,如果刚好在下边上,则填充上边的小正方形,填充颜色随机"""
        
turtle.speed(0)
turtle.delay(0)
turtle.dot(10,'red')
turtle.penup()
turtle.goto(-250,250)

for i in range(11):
    turtle.pd()
    turtle.fd(500)
    turtle.bk(500)
    turtle.pu()
    turtle.right(90)
    turtle.fd(50)
    turtle.left(90)

turtle.penup()
turtle.goto(-250,250)
turtle.right(90)
for i in range(11):
    turtle.pd()
    turtle.fd(500)
    turtle.bk(500)
    turtle.pu()
    turtle.left(90)
    turtle.fd(50)
    turtle.rt(90)
turtle.penup()
turtle.home()
turtle.ht()

screen = turtle.Screen()
screen.onclick(lambda x,y:fill_square(x,y))  # 单击会调用fill_square函数在x,y处进行填充
screen.mainloop()


发表在 python, turtle | 留下评论

turtle狗绕五边形练习题

turtle的Python编程狗绕五边形
仔细观察图形,请同学们把下面画扇形的代码定义成一个函数,重新编程!

import turtle

d = 50
for i in range(5):
    turtle.fd(50)
    turtle.left(72)

for i in range(2):
    turtle.fd(d)
    turtle.left(72)
turtle.fd(d/2)

turtle.right(90)
turtle.circle(-d/2,72)
turtle.right(90)
turtle.fd(3*d/2)
turtle.right(180)
turtle.fd(3*d/2)
turtle.right(90)
turtle.circle(-3*d/2,72)
turtle.right(90)
turtle.fd(5*d/2)
turtle.right(180)
turtle.fd(5*d/2)
turtle.right(90)
turtle.circle(-5*d/2,360-108)

turtle.right(90)
turtle.fd(3*d/2)
turtle.right(180)
turtle.fd(3*d/2)
turtle.right(90)
turtle.circle(-3*d/2,72)

turtle.right(90)
turtle.fd(d/2)
turtle.right(180)
turtle.fd(d/2)
turtle.right(90)
turtle.circle(-d/2,72)

turtle.ht()
turtle.done()

发表在 python, turtle | 标签为 | 留下评论

调用np.linspace进行线性插入坐标点


import numpy as np

def insert_points2(start,end,amounts):
    """start:起始坐标,end:结束坐标,amounts:要生成的点数"""
    xs = np.linspace(start[0],end[0],amounts)
    ys = np.linspace(start[1],end[1],amounts)
    return list(zip(xs,ys))

def insert_points(start,end,amounts):
    """start:起始坐标,end:结束坐标,amounts:要生成的点数"""
    xy = np.linspace(start,end,amounts)
    return [tuple(cors) for cors in xy]

start = (0,0)
end = (100,100)
ps = insert_points(start,end,11)
print(len(ps))
print(ps)

发表在 numpy, python | 留下评论

求10的算术平方根Python运行过程图示表

李兴球Python求10的算术平方根Python运行过程图示表

def sqrt(a):
    """本函数求a的算术平方根"""
    left = 0
    right = a    
    while True:
        x = (left+right)/2
        if x*x>a:  # 如果x的平方比a还要大,说明right值大了
            right = x
        elif x**2
							
发表在 python | 标签为 | 留下评论

tkinter之星光旋转2D向量与面向对象编程适合初三学过三角函数以上同学

李兴球Python之tkinter星光旋转

"""
   tkinter星光旋转.py
   面向对象编程案例, 本程序适合于初三以上学习过三角函数的学生学习,
   作者: 李兴球  2022/9/16
"""
import time
import math
import random
from tkinter import *

class Vector2D(tuple):
    """2D向量类"""    
    def __new__(cls, x, y):
        return tuple.__new__(cls, (x, y))
    
    def __sub__(self, other):
        return Vec2D(self[0]-other[0], self[1]-other[1])
    
    def rotate(self,angle=1):
        perp = Vector2D(-self[1], self[0])
        angle = angle * math.pi / 180.0
        c, s = math.cos(angle), math.sin(angle)
        return Vector2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s)    
        
class Point:   # 表示一个点的类
    def __init__(self,x,y,canvas):
        self.x = x
        self.y = y
        self.cv = canvas
        # 创建一个'实体'点
        self.item = cv.create_oval(x,y,x+1,y+1,fill='white')

    def rotate(self,center=(0,0),degree=-1):
        x1,y1,x2,y2 = self.cv.coords(self.item)
        points = [(x1,y1),(x2,y2)]
        points= [Vector2D(x,y) for x,y in points] # 转换为向量
        points = [C-center for C in points]
        points = [C.rotate(degree) for C in points]
        points = [C+center for C in points]
        points = [points[0][0],points[0][1],points[1][0],points[1][1]]
        self.cv.coords(self.item,points)

if __name__ == '__main__':
    
    root = Tk()
    cv = Canvas(root,bg='black',width=800,height=800)
    cv.pack()

    # 创建2000个点
    points = [(random.randint(-800,800),random.randint(-800,800))
              for i in range(2000)]

    dots = [Point(x,y,cv) for x,y in points] # 实例化2000个点

    while True:
        [d.rotate() for d in dots]
        cv.update()
        

发表在 python, tkinter | 标签为 , | 留下评论

填充块飞了

李兴球Python填充块飞了一个基本程序,把它应用起来价值就大了,具体发挥看你自己,这可是个秘密,不过一般人无法识别。

import time
import turtle

for i in range(4):
    turtle.fd(100)
    turtle.left(90)

turtle.fd(150)
turtle.penup()

turtle.fillcolor('red')
turtle.begin_fill()
for i in range(4):
    turtle.fd(100)
    turtle.left(90)
turtle.end_fill()

t = turtle.getturtle()
k = t.items[-1]

cv = turtle.getcanvas()
for i in range(200):
    cv.move(k,-1,1)
    cv.update()
    time.sleep(0.01)

发表在 python, turtle | 留下评论

不用三角函数实现的多点绕一个中心点旋转?

李兴球Python不绕中心点旋转turtle
import time
import turtle

def godot(x,y):
turtle.goto(x,y)
turtle.dot(10,’red’)

def rotate(center,degree,*points):
“””一些点绕着center点旋转,每次旋转degree度
points是不定长参数,一个元组里面有一些点
“””
points = [B-center for B in points]
points = [C.rotate(degree) for C in points]
points = [C+center for C in points]
return points

turtle.penup()
turtle.goto(-100,-100)
turtle.begin_poly()
for i in range(5):
turtle.fd(100);turtle.dot(10,’red’)
turtle.left(72)
turtle.end_poly()
dots = list(turtle.get_poly())
dots.pop()
A = sum([x for x,y in dots])/len(dots),sum([y for x,y in dots])/len(dots)

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

发表在 python, turtle | 标签为 | 留下评论

旋转的几何体_纯turtle

李兴球Python旋转的几何体
import time
import turtle

def draw_polygon(pc,fc=”,sz=5,*points,):
turtle.color(pc,fc)
turtle.pensize(sz)
turtle.penup()
turtle.goto(points[0])
turtle.pd()
turtle.begin_fill()
for p in points[1:]:
turtle.goto(p)
turtle.goto(points[0])
turtle.end_fill()

turtle.bgcolor(‘black’)
jack = turtle.Turtle(‘blank’)
jack.penup()
jack.sety(200)
jack.color(‘white’)
jack.write(‘旋转的几何体by李兴球2022/9/10′,
align=’center’,
font=(‘微软雅哧’,22,’normal’))

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

发表在 python, turtle | 标签为 | 留下评论

python turtle 旋转的文字之秘密代码

李兴球Python turtle 旋转的文字
“””旋转文字.py”””

“””在Python海龟画图中能把写的文字进行旋转吗?
多少年前我就在想这个问题,我还特别编写了一个叫sprites的模块来一一解决我所有自行突发奇想的问题,
不过下面的程序不需要sprites模块了,也能让所写的文字旋转,你想学的话联系本人.
“””
import time
import turtle

#以下是写一些文字

turtle.write(‘已知DE=60,FB=80,角EAF=45度,求EF长度’,
align=’center’,font=(”,24,’normal’))

t = turtle.getturtle() # 得到海龟对象,
t.hideturtle() # 隐藏海龟对象
wz = t.items[-1] # 海龟对象的项目中的最后一个项目
cv = turtle.getcanvas() # 得到画布对象
a = 0

# 下面是付费内容,呵呵呵

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

发表在 python, tkinter, turtle | 留下评论

python海龟几何数学编程之_正方形67度角求另一角问题

python初等几何问题
如题,用海龟做界面,内核当然是想办法编写代码把角度求出来,那如何编写程序呢? 以下是代码:

import turtle

d = 180                        # 正方形的边长
turtle.pensize(2)
for i in range(4):
    turtle.fd(d)
    turtle.left(90)

# 下面是画BF线段
turtle.left(22)
turtle.fd(50)
tmp = turtle.position()
BF = Line((0,0),tmp)
DC = Segment((d,d),(d,0))
r = BF.intersection(DC)
F = r[0]
turtle.goto(F)
turtle.home()

# 下面是画BE线段
turtle.left(67)
turtle.fd(50)
tmp = turtle.position()
BE = Line((0,0),tmp)
AD = Segment((0,d),(d,d))
r = BE.intersection(AD)
E = r[0]
turtle.goto(E)

turtle.goto(F)               # 到达F点
je = turtle.towards(E.x,E.y) # 返回朝向E点的角度值
#turtle.setheading(je)
角BFE = 22 + 180 - je
print(角BFE)

turtle.ht()

如果你运行不了上面的代码,那找我即可完美解决!

发表在 python, turtle | 留下评论

正弦演绎

Python正弦动画演示

"""
   正弦演绎.py,正弦是三角形一个锐角的对边长度除以斜边长度的值,
   而余弦则是邻边长度除以斜边长度的值,请修改程序,显示余弦值,
   余弦记作cos(angle)
"""
import time
import turtle
from sympy import *

def mark(w,pos,char,bg,fg):
    """标注一个符号在圆点上,pos:坐标,char:字符,bg:背景色,fg:前景色"""
    c = w.pencolor()       # 记录画笔颜色
    w.penup()
    w.goto(pos)
    w.pencolor(fg)    
    w.dot(20,bg)
    w.sety(w.ycor()-8)
    w.setx(w.xcor()+2)    
    w.write(char,align='center',font=('',12,'normal'))
    w.sety(w.ycor()+8)
    w.setx(w.xcor()-2)
    w.pencolor(c)
    
def draw_line(w,l):
    p1,p2 = l.points
    p1,p2 = p1.evalf(),p2.evalf()     
    w.penup()
    w.goto(p1)
    w.pd()
    w.goto(p2)
    w.pu()
    
def draw_arc(w,radius,angle):
    """w是海龟,radius是弧的半径,angle是角度"""
    w.home();w.fd(radius);w.left(90)
    w.pd();w.circle(radius,angle);w.pu()
    
turtle.tracer(0,0)
turtle.speed(0);turtle.ht()
turtle.fd(300);turtle.stamp();turtle.bk(600);turtle.fd(300);
turtle.left(90)
turtle.fd(300);turtle.stamp();turtle.bk(600);turtle.home()

p0 = Point(0,0)
ab = Segment(p0,Point(250,0))         # 线段

turtle.sety(200);turtle.write('正 弦 演 绎',align='center',font=('',22,'bold'))

w = turtle.Turtle('blank')
w.speed(0)
draw_line(w,ab)

for angle in range(1,61):    # 角度制的度数
    w.clear()    
    ac = ab.rotate(angle*3.1415926/180,p0) # 绕p0旋转(如果用pi,会很慢)
    
    C = ac.points[1]         # C点
    B = Point(C.x,0)         # B点
    cb_len = C.y             # cb的长度就是C点y坐标    
    value = cb_len / ac.length   # 角CAB的正弦值,对边/斜边
    value = value.evalf()
    
    draw_line(w,ac)
    draw_line(w,Line(C,B))
    draw_arc(w,20,angle)
    w.goto(0,-100)
    s = "sin(" + str(angle) + ")= BC/AC = " + str(value)
    w.write(s,align='center',font=('',14,'normal'))
    mark(w,(-15,-15),"A","blue","white")
    mark(w,(B.x,-15),"B","blue","white")
    mark(w,(C.x,C.y+15),"C","blue","white")

    turtle.update()    



发表在 python, turtle | 留下评论

如何在turtle画虚线呢

以下是画虚线的方法,其实就是tkinter的代码,因为turtle本来就是基于tk开发的,所以只要去查turtle.py的源代码就能写出代码。代码如下所示:

import turtle

t = turtle.getturtle()
cv = turtle.getcanvas()
print(t.currentLineItem)
cv.itemconfig(t.currentLineItem,dash=(4,4))
t.fd(100)
t.fd(100)
t.penup()

t.right(90)
t.pendown()
t.fd(100)

在绘制几何图的时候,添加辅助线,这个时候可以把线条设为虚线,你学会了吗?

发表在 python, turtle | 标签为 | 留下评论

古埃及数拆分程序

某个人突然发了一道题目让我做,我出了个价,然后就没有然后了。不过我还是做了一下,下面是我的代码:
他看到后能在这里免费拿到代码了,不需要花money了。

"""
  把分数分解来古埃及分数,如4/9可以分解为1/3加上1/9.
  要求分子都是1。这是我的一个解法。
"""
import math

def sub(a,b,c,d):
    """两个分数相减,以二元组表示一个分数"""
    return a*d-c*b,b*d
    
a=int(input('分子:'))
b=int(input('分母:'))
f=a,b

m = 2
lis = []
while True:
    if 1*f[1] > m * f[0]:m=m+1

    elif 1*f[1] == m * f[0]:
        lis.append(m)
        break
    else:
        f = sub(f[0],f[1],1,m)
        lis.append(m)
        
print(lis)

发表在 python | 留下评论

灵境之梦最新版_李兴球创意简介

李兴球创意简介灵境之梦
这是一个用Python制作的多媒体动画展示程序,以下是所有源代码:

"""
   灵境之梦.py   本程序需要Python精灵模块运行,安装方法: pip install sprites。如果不会安装,请加微信scratch8进行技术支持。
"""
import time
import random
from sprites import *                           # 从精灵模块导入所有命令

screen = Screen()                               # 新建屏幕 
screen.setup(520,620)                           # 设定宽高 
screen.bgpic('封面.png')                        # 贴上背景
screen.title('灵境之梦__by__李兴球')         # 写上标题

ti = Sprite(visible=False)                   # 显示作品的名字
ti.sety(220)
ti.color('white')
ti.write('灵境之梦',align='center',font=('楷体',30,'bold underline'))

ims = [f"素材/{i}.jpg" for i in range(12)]   # 新建一些角色,每个角色就是一张图片.
sps = [Sprite(shape=im) for im in ims]
for i in range(12):
    sps[i].rotatemode(1)                    # 设定旋转模式为左右翻转
    sps[i].setheading(i*30)

PlaySound('metauni.wav',SND_LOOP|SND_ASYNC)  # 循环播放背景音乐

counter = 0                                  # 下面是一些图片抖动并散开,最后反弹的代码段
while True:                                  # 让图片擅抖动散开
    pic = sps[counter%12]
    if not pic.collide_edge():               # 如果没有碰到边缘
        pic.fd(random.randint(-4,8))
    counter += 1
    if counter==1100:break
    time.sleep(0.01)
i = 0
while i<10000:                            # 重复10000次
     pic = sps[i%12]
     pic.fd(3)
     pic.bounce_on_edge()                 # 碰到边缘就反弹
     i = i + 1
[sp.hide() for sp in sps]                 # 全部隐藏

feng = Sprite("feng")                     # 显示带VR眼睛的男孩图片
for _ in range(6):
    feng.nextshape()                      # 下一个造型
    time.sleep(0.01)

[feng.setalpha(a) for a in range(255,100,-10)]     # 设定透明度

txt = "Hi,大家好,我是头号编程玩家"     # 显示一些文字,赋予作品一些内涵
zi = Sprite(visible=False)               # 新建隐藏的角色
zi.goto(-120,180)
zi.color('yellow')
for t in txt:
    zi.write(t)
    zi.fd(15)
    time.sleep(0.1)
zi.goto(0,100)
zi.color('green')
zi.write2('李兴球',align='center',font=('',48,'normal'))

texts = ['我做了一个灵境之梦。','梦见未来人们把意识上传到灵境玩去了。',
         '世界全部由人工智能全自动控制。', '但我,却是极少数还在真实世界的人类。',
         '本程序由Python精灵模块开发,代码:80行','Python,值得你拥有!本程序下载网址:']
y = 50
for txt in texts:
    zi.goto(0,y)
    if y==-150:
        zi.color('yellow')
    else:
        zi.color('white')
    zi.write(txt,align='center',font=('楷体',18,'normal'))
    zi.wait(1)    
    y = y - 50
zi.bk(180)
x  = zi.xcor()
zi2 = Sprite(shape='blank')
zi2.color('white')
s = 'www.lixingqiu.com'

zi.goto(x+150,y-45)
zi.color('lime')
zi.write('基于Python海龟画图模块的创造',align='center',font=('',12,'italic'))
while True:
    zi2.clear()
    zi2.goto(x,y)
    zi2.sety(y)
    for char in s:
        zi2.write(char,font=('',20,'normal'))
        zi2.wait(0.1)
        zi2.fd(20)
    
screen.mainloop()



发表在 python, sprites | 留下评论

漫水填充bloodfill4原理程序

#bloodfill漫水填充原理程序
#img表示一张图像,里面的1表示一种颜色,r,c为起始填充点
#把r,c四方向相邻的点都变成2这种颜色,四方向递归进行

def fill(img ,r,c,oldcolor,newcolor):
    if r>=0 and r<5 and c>=0 and c<5:
        if img[r][c] == oldcolor:
            img[r][c] = newcolor
            fill(img ,r-1,c,oldcolor,newcolor)
            fill(img ,r+1,c,oldcolor,newcolor)
            fill(img ,r,c+1,oldcolor,newcolor)
            fill(img ,r,c-1,oldcolor,newcolor)
            
     
img = [[1,1,0,1,1],
       [1,1,1,0,1],
       [1,1,0,1,0],
       [1,1,1,0,1],
       [0,0,1,0,0]]
r,c = 1,1
fill(img,1,1,1,2)
for row in img:
    print(row)
       

发表在 python | 留下评论

海龟碰到线条就停止了(也是为了bloodfill漫水填充而编的测试程序)

#海龟碰到线条就停止了(也是为了bloodfill漫水填充而编的测试程序)
import turtle

cv = turtle.getcanvas()
turtle.shape('circle')
turtle.shapesize(0.2)
 
turtle.circle(100)

turtle.penup()
turtle.sety(50)
running = True
while running:
    turtle.fd(1)
    all_items = cv.find_all()
    for item in all_items:
        zt = cv.itemconfig(item)['state'][-1]
        if zt=='hidden':continue
        selfitem = turtle.getturtle().turtle._item
        x1,y1,x2,y2 = cv.bbox(selfitem)
        ss = cv.find_overlapping(x1,y1,x2,y2)
        ss = set(ss)
        ss.remove(selfitem)
        if ss:running = False
        
x,y = 100,100
cv.create_rectangle(x,y,x,y,outline="red")
x,y = 200,100
cv.create_line(x,y,x+1,y+1,width=1,fill="red")

发表在 python, turtle | 留下评论

获取tkinter画布上的像素值(为了bloodfill漫水填充而准备的程序)

获取tkinter画布上的像素值(为了bloodfill漫水填充而准备的程序)

from tkinter import *
from PIL import Image
import numpy as np

def get_pixel_color(canvas, x, y):
    """获取tkinter画布上一点的像素值,原理是寻找最上层item,但是如果item表示的是文字
       则返回的并不代表文字区域都是那个fill颜色,因为文字并不是实心的,所以此程序局限性较大,
       也不适合于有图像的.仅做参考,供给有需要的人士阅读"""
    ids = canvas.find_overlapping(x, y, x, y)

    if len(ids) > 0:                 # 说明画布上有item,取最上面的item 
        item = ids[-1]
       
        color = canvas.itemcget(item,"fill") # 获取这个item的fill填充颜色
        color = color.upper()
        if color != '':r,g,b = canvas.winfo_rgb(color)
    else:                            # 否则画布上这个位置没有item,则取背景色     
        r,g,b = canvas.winfo_rgb(canvas.config('bg')[-1])
    r,g,b = r>>8,g>>8,b>>8
    return r,g,b

def get_pixels_of(canvas):
    width = int(canvas["width"])
    height = int(canvas["height"])
    colors = []

    for y in range(height):
        row = []
        for x in range(width):
            row.append(get_pixel_color(canvas, x, y))
        colors.append(row)

    return colors


root  = Tk()
cv = Canvas(width=48,height=36,bg='cyan')
cv.pack()
画布背景色 = cv.winfo_rgb(cv.config('bg')[-1])
r,g,b = 画布背景色
r,g,b = r>>8,g>>8,b>>8
print(r,g,b)

cv.create_text(22,22,text='我',fill='red')

cv.create_oval((5,5,20,16),fill='red',outline='red')
ps = get_pixels_of(cv)

# 把ps中的每个点写入图像
#im = Image.new("RGBA",(480,360))
ps = np.array(ps)
print(ps)

im = Image.fromarray(np.uint8(ps))
im.show()





发表在 python, tkinter | 留下评论

bloodfill漫水填充海龟探索程序

以下程序是BUG程序,填充不完整,填充采用fill4即4方向填充,速度也慢,图像大了会有stack溢出,本人只是用来测试。

import turtle

def get_pixel_color(canvas, x, y):
    ids = canvas.find_overlapping(x, y, x, y)

    if len(ids) > 0:                 # 说明画布上有item,取最上面的item 
        item = ids[-1]
       
        color = canvas.itemcget(item,"fill") # 获取这个item的fill填充颜色
        color = color.upper()
        if color != '':r,g,b = canvas.winfo_rgb(color)
    else:                            # 否则画布上这个位置没有item,则取背景色     
        r,g,b = canvas.winfo_rgb(canvas._canvas.config('bg')[-1])
    r,g,b = r>>8,g>>8,b>>8
    return r,g,b
    
def fill(canvas,x,y,oldcolor,newcolor):
  
     if y<=abs(height//2) and x<=abs(width//2):
          y = -y
          ss = None
          all_items = cv.find_all()
          for item in all_items:
             zt = cv.itemconfig(item)['state'][-1]
             if zt=='hidden':continue
             ss = cv.find_overlapping(x,y,x,y)
             #print('ss=,',ss)
             if ss:break
         
          if ss == None or (isinstance(ss,tuple) and len(ss)==0 ):
              
             se = get_pixel_color(canvas, x,y)
            #print('se=',se)
             if se == oldcolor:
                i = cv.create_line(x,y,x+1,y+1,width=1,fill=newcolor)
                #print(cv.coords(i))
                cv.update()
                fill(canvas ,x,-y+1,oldcolor,newcolor)
                fill(canvas ,x,-y-1,oldcolor,newcolor)
                fill(canvas ,x+1,-y,oldcolor,newcolor)
                fill(canvas ,x-1,-y,oldcolor,newcolor)

turtle.delay(0)
turtle.speed(0)
width = turtle.window_width()
height = turtle.window_height()          
cv = turtle.getcanvas()
turtle.shape('circle')
turtle.shapesize(2) 
turtle.circle(10)
turtle.ht()
fill(cv,5,5,(255,255,255),'red')

发表在 python, tkinter, turtle | 留下评论

turtle发射任务_少儿Python课堂练习

李兴球Python发射任务演示效果
上课了,请同学们仔细阅读代码,完成发射任务,具体请见演示动画。

import time
import turtle

def shoot_b1():
    """请完善这个函数的代码"""
turtle.delay(0)
turtle.setup(480,360)

b1 = turtle.Turtle('circle')
b1.left(90)
b1.speed(0)
b1.penup()
b1.ht()

cv = turtle.getcanvas()
按钮1 = turtle.TK.Button(text='发射',command=shoot_b1)
cv.create_window(0,150,window=按钮1)

square = turtle.Turtle('square')
square.shapesize(2)
square.ht()
square.penup()
square.goto(-240,150)
square.st()
dx = 2
while True:

    square.fd(dx)
    if square.xcor()>=240:
        square.ht()
        square.goto(-240,150)
        square.st()
   pass                      # 请在这里完善代码
        
    if b1.isvisible():
        b1.fd(10)
        if b1.ycor()>180:b1.ht()
    turtle.update()
    time.sleep(0.01)
发表在 python, tkinter, turtle | 留下评论

按钮事件初探_随机生成海龟

按钮事件初探_随机生成海龟


"""
  按钮事件初探_随机生成海龟.py
  
  2022年6月4号下午4点Python班课堂编程任务
  
  任务一:
  单击按钮会在随机位置生成不同颜色及大小的海龟,并放在一个字典中,
  字典的键盘就是海龟,值是它的颜色 (如果用RGB1.0模式表示颜色,那么值就是一个三元组)

  任务二:
  在按钮下面再加一个按钮,单击它后会修改成随机的背景颜色,同时所有海龟的y坐标会取反,
  即改变为原来y坐标的负数.
  
"""
import turtle

def process_click():    
    print('什么也没做')

turtle.setup(800,600)
canvas = turtle.getcanvas()

# 新建按钮,上面的文本是'点我生成海龟',单击事件是process_click
button1 = turtle.TK.Button(text=' 点 我 生 成  海 龟 ',command=process_click)
# 把按钮放在画布上,这里的坐标是以中心点为原点,但y轴向下为正!
canvas.create_window(0,150,window=button1 )


turtle.done()

发表在 python, tkinter, turtle | 留下评论

只记今朝笑_生日快乐贺卡

李兴球Python只记今朝笑_生日快乐贺卡

"""
    只记今朝笑_生日快乐贺卡.py    
"""
from sprites import *

width,height = 450,700            # 窗口宽度和高度

screen = Screen()
screen.bgcolor('#3DA290')
screen.setup(width,height)
screen.title('生日快乐贺卡')

logo = Sprite('cake.png',pos=(-500,70))
logo.setalpha(0)
aa = 0
def display_logo():
    global aa
    if aa<255:
        aa = aa + 1
        logo.setalpha(aa)        
        screen.ontimer(display_logo,10)
logo.goto(0,10)
display_logo()                    # logo渐显

music = '胡伟立 - 只记今朝笑(快乐得不得了)贺岁童唱版.wav'
lrc = '只记今朝笑(贺岁童唱版).lrc'
singer = Sprite('blank')
singer.sety(-320)
singer.play(music,lrc,fontstyle=("",20,"normal"))

# 标题文字从左到右旋转而来,在中间通过stamp印于屏幕上,继续旋转向右直到消失
txt2image('生日快乐','res/tcgame.png',fontsize=44,color='magenta')
tctitle = Sprite('blank',pos=(0,280))
tctitle.bk(400)
tctitle.left(40)
tctitle.shape('res/tcgame.png')
clock = Clock()
for _ in range(800):
    tctitle.addx(1)
    if tctitle.xcor()==0:tctitle.stamp()
    tctitle.right(1)
    clock.tick(120)
ft = ('',22,'normal')
tctitle.hide()

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

发表在 python, sprites | 标签为 | 留下评论

吐泡泡的小金鱼

fish小金鱼李兴球Python

import random
from sprites import *

def rise(self):
    if self.ycor()<180:
        self.addy(4)
        self.screen.ontimer(self.rise,50)
    else:
        self.ht()
        
def spit_bubble(self):
    if not self.bubble.isvisible():
       self.bubble.goto(self.position())
       self.bubble.shape('circle.png')
       self.bubble.show()
       self.bubble.rise()

Sprite.rise = rise
Sprite.spit_bubble = spit_bubble

screen = Screen()
screen.setup(480,360)
screen.bgpic('underwater.png')

fish1 = Sprite('fish.png')
fish1.bubble=Sprite('blank',visible=False)

clock = Clock()
while True:
    fish1.fd(5)
    if random.randint(1,10)==1:
        fish1.spit_bubble()
    fish1.bounce_on_edge()
    fish1.right(random.randint(-20,20))
    screen.update()
    clock.tick(30)

发表在 python, sprites | 标签为 | 留下评论

积分演绎

李兴球Python积分演绎

"""
  积分演绎
  在二次函数x*x/200的x区间为[0,240]曲线和x轴之间的面积是多少?
  这可以通过scipy的quad命令求出,这里我们逐步逼近来求,也就是演示积分的一个原理。
  求积分用下面的代码:
  from scipy.integrate import quad
  area = quad(lambda x:x*x/200,0,240)
"""
import numpy as np
from sprites import *

c = Turtle()
c.pendown()
c.fd(300)
c.stamp()
c.bk(600)
c.fd(300)
c.left(90)
c.fd(300)
c.stamp()
c.bk(600)
c.home()
c.penup()

# y = x*x / 200             # 二次函数
f = lambda x: x*x/200
for x in range(240):
    c.goto(x,f(x))
    c.dot(2)
m = Sprite('blank')
t = Sprite('blank',pos=(-200,200))
step = 40
while step>0.01:
    m.clear()
    a = np.arange(0,240,step)
    area =0
    s = 0
    for x in a:
        y = f(x)
        m.goto(x,0)
        m.pendown()
        m.goto(x,y)
        m.goto(x+step,y)
        m.goto(x+step,0)
        m.goto(x,0)
        m.penup()
        s = step * y
        area += s
    t.clear()
    ds = '和面积:23040相差:' + str(23040-area)
    t.write(ds,font=('黑体',32,'normal'))
    t.wait(1)    
    step = step/2
 
c.ht()
screen.mainloop()



发表在 python, sprites | 标签为 | 留下评论

海龟命令学习器

李兴球Python海龟命令学习器

from sprites import *

def exit_program():
   screen.bye()

screen = Screen()
screen.setup(580,460)
root = screen._root
canvas = screen.getcanvas()
screen.bgcolor('light cyan')

t = Sprite('res/turtle2.png')
t.pendown()

frame = TK.Frame(canvas)
frame.grid(row=0,column=1)          # 这里一定要用grid布局

# 标签
label = TK.Label(frame, text= "请选择", font= ('Helvetica 14 bold'))
label.grid(row=0,column=0)

# 选择画笔颜色
def select_pencolor():
    s = askcolor()
    if s[-1]: t.pencolor(s[-1])
    
b1  = TK.Button(frame, text= "画笔颜色", command= select_pencolor)
b1.grid(row=1,column=0)

# 选择填充颜色
def select_fillcolor():
    s = askcolor()    
    if s[-1]: t.fillcolor(s[-1])
    
b2  = TK.Button(frame, text= "填充颜色", command= select_fillcolor)
b2.grid(row=2,column=0)

# 前进
b3  = TK.Button(frame, text= "前进forward", command=lambda :t.fd(10))
b3.grid(row=3,column=0)

# 右转
b4  = TK.Button(frame, text= "右转", command=lambda :t.rt(10))
b4.grid(row=4,column=0)

# 线宽
def input_pensize():
    w = screen.inputbox('输入','画笔线宽')
    if w.isdigit():
        print(w)
        t.pensize(int(w))
    
b5  = TK.Button(frame, text= "画笔线宽", command=input_pensize)
b5.grid(row=5,column=0)

# 手动输入命令
def run(event):
    cmd = b6.get()
    exec(cmd)
    
b6  = TK.Entry(frame, width=20)
b6.bind("",run)
b6.grid(row=6,column=0)


root.mainloop()

发表在 python, sprites | 标签为 | 留下评论

微分演绎

李兴球Python微分演译

"""
  微分演绎.py
  本函数演示二次函数 y = x*x/200在某点的微分,或者说变化率,即斜率k。
  在本例中的取x为100处的导数,根据求导公式,y的导函数应该是0.01x,
  所以在x为100处,斜率应该是1,所以y的值是100*100/200。
  sprites模块为turtle模块增强版。
  本程序没有用到Python精灵模块的增强功能,可稍加修改为turtle模块实现。
"""
from sprites import *

c = Turtle()
c.pendown()
c.fd(300)
c.stamp()
c.bk(600)
c.fd(300)
c.left(90)
c.fd(300)
c.stamp()
c.bk(600)
c.home()
c.penup()
c.goto(100,-20)
c.write('(100,0)',align='center',font='楷体 12 normal')
# y = x*x / 200             # 二次函数
f = lambda x: x*x/200
for x in range(-240,240):
    c.goto(x,f(x))
    c.dot(2)
    
m = Sprite('blank')
m.pensize(2)

step = 100
x0 = 100
while step>0.01:
    m.clear()
    m.goto(x0,0)
    m.pendown()
    m.goto(x0,f(x0))
    m.up()
    m.goto(x0+step,0)
    m.pendown()
    m.goto(x0+step,f(x0+step))
    m.up()
    k = (f(x0+step)-f(x0))/step  # 变化率    
    b = f(x0) - k * x0
    k,b = round(k,6),round(b,6)
    
    first = 0,b
    second = 200, k*200 + b
    m.goto(first)
    m.down()
    m.goto(second)
    m.up()
    step = step/1.1
    m.goto(0,-150)
    m.write(f'斜率:{k},   y截距:{b}',align='center',font='楷体 22 normal')
    m.wait(0.2)
 
c.ht()
c.screen.mainloop()



发表在 python, sprites | 留下评论

密室寻宝

李兴球Python封面密室寻宝

"""
   密室寻宝.py
"""
from sprites import *

screen = Screen()
screen.bgcolor('black')
screen.setup(480,360)
screen.title('密室寻宝')

cv = screen.cv

h = Sprite('blank')
h.saybordercolor('cyan')
h.saycolor('light green')
h.sayfontstyle(('楷体',22,'normal'))
h.say('据说密室尽头有宝藏')
h.say('上下左右方向箭头\n操作我先去拿钥匙',delay=4)
screen.bgcolor('light cyan')

def config_capstyle():
    lid  = d.currentLineItem
    cv.itemconfig(lid,capstyle=TK.BUTT,
              joinstyle=TK.MITER)

# 画的红色的墙是不能碰的
d = Sprite('blank')
d.pensize(20)
d.color("#FF0000")

config_capstyle()
d.goto(-230,180)
d.down()
d.addy(-100)
d.up()

d.pensize(40)
config_capstyle()
d.goto(0,180)
d.down()
d.addy(-150)
d.up()

config_capstyle()
d.goto(120,180)
d.down()
d.addy(-120)
d.up()

d.pensize(20)
config_capstyle()
d.goto(-120,80)
d.down()
d.addy(-180)
d.addx(360)
d.up()

sp1 = Sprite('res/sword.png',pos=(-220,-120))
def sp1_rotate():
    sp1.lt(10)
    screen.ontimer(sp1_rotate,100)
sp1_rotate()

sp2 = Sprite('res/egg.png',pos=(120,-50))
def sp2_rotate():
    sp2.rt(10)
    screen.ontimer(sp2_rotate,100)
sp2_rotate()

sp3 = Sprite(['res/bat1.png','res/bat2.png'],pos=(0,-50))
sp3.scale(0.2)
sp3.rotatemode(2)
sp3.right(90)
def sp3_move():
    sp3.fd(2)
    if sp3.find_overlapping():
        sp3.right(180)
    sp3.nextshape()
    screen.ontimer(sp3_move,100)
sp3_move()

key = Sprite('res/key.png',pos=(200,160))
key.scale(0.5)

player = Sprite('res/mask0.png',pos=(220,-140))
player.scale(0.3)

leftkey = Key('Left')                   # 新建左方向箭头
rightkey = Key('Right')                 # 新建右方向箭头
upkey = Key('Up')                       # 新建上方向箭头
downkey = Key('Down')                   # 新建下方向箭头
screen.listen()                         # 监听屏幕按键 
clock = Clock()

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

发表在 python, sprites | 留下评论

89的回文数之路_Python练习题

一个数正读反读都一样,我们就把它叫做“回文数”。随便选一个数,不断加上把它反过来写之后得到的数,直到得出一个回文数为止。例如,所选的数是 67,两步就可以得到一个回文数 484:

67 + 76 = 143

143 + 341 = 484

把 69 变成一个回文数则需要四步:

69 + 96 = 165

165 + 561 = 726

726 + 627 = 1353

1353 + 3531 = 4884

89 的“回文数之路”则特别长,要到第 24 步才会得到第一个回文数,8813200023188。

请编写程序,把89的回文数之路中产生的每个整数以换行输出。

程序如下所示:

 

"""
回文数之路.py
"""

n = '89'
while True:    
    n = int(n) + int(n[::-1])
    print(n)
    if str(n) == str(n)[::-1]:break
    n = str(n) 
发表在 python | 留下评论

青少年软件编程(Python)等级考试试卷(六级)

青少年软件编程(Python)等级考试试卷(六级)

编写:李兴球

分数:100.00            题数:37

 

一、单选题(共25题,每题2分,共50分)

  1. 一般情况下,下列哪种后缀名的文件不是文本文件?( )

 

A、.py

B、.txt

C、.bat

D、.png

 

  1. 以下代码打开一个文件,以下描述正确的是。( )

f = open(‘c:/在水一方.wav’,mode=’r’)

c = f.read

f.close()

A、由于.wav是二进制文件,所以第一行代码就错了。

B、c是一个字符串。

C、c是一个二进制的字节对象。

D、程序能正常运行。

 

  1. 关于下面程序,描述正确的是。( )

import json

 

d = dict(name=’张三’,age=12)

with open(‘c:/a.json’,mode=’w’) as f:

json.dump(d,f)

A、文件没有被正确关闭。

B、生成的a.json文件里有汉字。

C、用with自动管理资源能自动关闭文件。

D、保存的文件不是文本文件。

 

  1. 关于以下代码,描述 错误的是( )

 

import random

import turtle

 

cs = [‘red’,’green’,’blue’,random,turtle]

ts = [turtle.Turtle() for _ in range(3)]

[t.setheading(i*120) for i,t in enumerate(ts)]

[t.fd(100) for t in ts]

[t.color(c) for t ,c in zip(ts,cs[:3])]

 

A、cs列表中有两个模块名,理论上没有任何问题。

B、ts列表中有三只海龟。

C、每只海龟的方向都是一样的。

D、每只海龟的颜色不一样,并且都前进100个单位。

 

  1. 关于如下代码,描述正确的是( )

x = int(input())

s = ‘32,76,8’.split(‘,’)

e = [‘海洋’,’天空’,’宇宙’]

d = {}

for i in range(x):

d[s[i]] = e[i]

print(d)

A、只有输入3,程序才能运行正确。

B、输入5后,程序运行错误,并且d字典还是空字典。

C、如果输入字母,程序肯定出错。

D、第二行代码错误。

 

 

  1. 以下代码描述正确的是( )

import random

import numpy as np

a,b,c,d = [random.randint(1,10)for _ in range(4)]

a = np.array([[a, b], [c, d]])

print(a[0]+a[1])

 

A、由于用random.randint生成的最大整数是10,所以输出不可能超过20。

B、由于a被重新定义,而b,c,d还是整数,所以a不能和b,c,d进行相加操作了。

C、程序能正确运行。

D、由于最终a是二维数组,所以最后一行代码出错。

 

 

  1. 以下关于文件的描述,正确的是。( )

A、文件系统是组织数据的一种方式。

B、在Python中用open命令打开文件后不需要关闭。

C、二进制文件是不能用记事本打开的。

D、Python程序只能用IDLE进行编辑。

 

  1. 属于Python第三方库的是。( )

A、 turtle。

B、sys。

C、math。

D、matplotlib。

 

 

  1. 关于排序算法,以下说法正确的是( )

A、冒泡排序每趟循环必定是最大的数移到列表最右边。

B、选择排序每次循环从列表中选择最小的或者最大的,然后从剩下的数据中再次选择最小的或者最大的,依此类推。

C、Python中的列表用sort命令,只能让列表中的数据从小到大排序。

D、Python中的sorted命令是原地排序,返回为None。

 

 

  1. 关于以下程序,描述正确的是( )

import numpy as np

student = np.dtype([(‘name’,’S20′), (‘age’, ‘i1’)])

s1 = np.array([[‘翠花’,12],[‘大壮’,18]])

print(str(s1[0]).split()[-1])

 

A、最终输出一个列表。

B、s1其实是一个一维数组。

C、最终结果并不是一个字符串。

D、student表示numpy模块的一种数据类型。

 

  1. 以下代码运行后,输出的a,描述正确的是( )

import numpy as np

a = np.array([[1,2,3],[4,5,6]])

a.shape = (1,6)

print(a)

A、a是一个一维数组。

B、a是一个二维数组。

C、a[0]的值是1。

D、a[0][1]的值是1。

 

 

  1. f字符串表达式能格式化字符串,假设x =10,那么f”ab{x:03}”结果是( )

A、’ab010′

B、’ab 10′

C、’abxxx’

D、’abx03′

 

 

  1. python内置可视化界面模块tkinter中哪个命令用于新建按钮( )

A、Tkr

B、Label

C、Text

D、Button

 

 

  1. 关于SQlite数据库,以下描述不正确的是( )

 

A、它是由c语言编写的一个数据库系统。

B、数据库由多个磁盘文件组成。

C、由SQL查询语言进行数据库的操作。

D、一个不需要服务器支持的数据库系统。

 

  1. 代码class A:pass,以下选项不正确的是( )

A、a = A() ,实例化了一个对象叫a。

B、类的名称一定要大写开头。

C、a = A();print(a.x),代码会运行出错。

D、pass只是占位符。

 

 

  1. “ab{:03}”.format(10)的结果是( )

A、’ab001′

B、’ab010′

C、’ab333′

D、’ab100′

 

  1. 关于以下代码,以下描述正确的是( )

import numpy as np

import matplotlib.pyplot as plt

 

y = np.linspace(-10,10,20)

plt.plot(y)

plt.show()

A、显示的是一条曲线。

B、y所包含的值是-10到10之间的整数。

C、对y进行求和后的值是0.0

D、numpy模块是内置模块,不需要安装。

 

 

  1. GUI,即图形用户界面,它的英文全称是( )

 

A、graphical user interface

B、green user interface

C、gray ultra internet

D、good update  island

 

  1. turtle基于tkinter模块开发,导入turtle模块后可以用turtle.TK引用tkinter模块。那么tkinter.messagebox.showinfo和下面哪句代码含义一样( )

A、turtle.TK.messagebox

B、TK.showinfo

C、turtle.Turtle.messagebox

D、showinfo.turtle.TK

 

 

  1. “%c%cYou”%(73,10084)的运行结果的长度是( )

A、1

B、3

C、5

D、7

 

 

  1. 关于以下程序,描述正确的是( )

 

import sqlite3

import numpy as np

a = np.arange(1,10,2)

dbfiles = [f”c:/test_{i}.dat” for i in map(str,a)]

conns = [sqlite3.connect(fn) for fn in dbfiles]

[conn.close() for conn in conns]

 

A、将会在c盘根目录建立10个数据库

B、a是一个一维数组,包含5个偶数

C、conns是一个sqlite3的数据库连接对象

D、数据库名不一定以db为扩展名,也可以自定义为其它扩展名或没有扩展名

 

 

  1. 下面的程序,描述正确的是( )

A、如果再执行一遍list(m)将返回一个空列表。

B、由于第5行已经将m生成为列表,而第7行好像作同样的事情,所以第7行是多余的。

C、生成的文件名是test_55.txt。

D、第4行的m是一个二维数组。

 

 

 

  1. 执行下面代码,以下描述错误的是(  )

import turtle

 

class Ball:

def __init__(self,diameter,position):

self.diameter = diameter  # 直径

self.x,self.y = position        # 球的中心点坐标

self.dx = 3   # 水平单位位移

self.dy = 3   # 垂直单位位移

def move(self):

self.x += self.dx

self.y += self.dy

def draw(self,turtle):

turtle.goto(self.x,self.y)

turtle.dot(self.diameter)

 

turtle.penup()

turtle.speed(0)

turtle.delay(0)

turtle.hideturtle()

ball = Ball(100,(0,0))

while True:

turtle.clear()

ball.move()

ball.draw(turtle)

 

A、程序运行后,将会看到一个直径为100的圆形朝右上角移动。

B、在程序中,海龟起的作用是把圆形通过dot命令画出来。

C、 由于Ball类中的draw方法调用了turtle的相关命令,所以它是隐含继承turtle.Turtle类的。

D、 这是一个正确的程序

 

 

  1. 关于sqlite中的游标,以下说法错误的是( )

 

A、游标用来执行sql语句。

B、通过游标可以取得返回的记录。

C、不需要显式创建游标,用连接对象也能执行sql语句。

D、不能通过for循环直接遍历游标对象。

 

  1. 关于以下代码,不正确的描述是( )

class Test:

def __init__(self,n):

self.ns = n

 

def show(self):

print(self.ns)

 

A、实例化Test的代码是Test()。

B、ns是Test类的一个属性。

C、Test类并没有继承任何类。

D、self表示实例化后的对象,可以省略。

 

 

二、判断题(共10题,每题2分,共20分)

  1. tkinter模块用来做GUI程序,其实用turtle模块编制的程序也是GUI程序。(   )

 

  1. 执行ord(“%c”%(10084))的结果也是10084。( )

 

  1. 执行’中{:华>5}’.format(‘人’)后的结果有5个‘华’字。( )

 

  1. sqlite数据库可由一个或多个文件组成。(   )

 

  1. Python源文件扩展名一般为py ,并且一般是utf-8编码。( )

 

  1. 文件的读写操作并不是Python自带的,需要导入os模块。( )

 

  1. 用pip命令安装matplotlib的方法是pip install matplotlib。( )

 

  1. ‘255.0.123.55’.split(‘.’)执行后返回一些字符串。(  )

 

  1. 运行如下,结果是显示10个红色的圆点。 (    )

import matplotlib.pyplot as plt

plt.plot(range(10),’or’)

plt.show()

 

  1. 一个类继承自另一个类,那么这个类是另一个类的子类。( )

 

三、编程题(共2题,共30分)

  1. 数字记录与显示

 

编制程序,要求合理地运用time、sqlite3、numpy和matplotlib模块把输入的数字存储在数据库中,并且线性显示出来。程序输入10,那么生成10个在1到100范围内的整数。输入20,则在1到100范围内生成20个整数可视化地显示出来。输入小于1的数则程序结束。

输入10的图形可以参考下面图:

评分标准:

(1)正确地导入了所有要应用到的模块。(3分);

(2)所输入的数据都能进入数据库。(3分);

(3)能正确地使用matplotlib显示数据。(3分);

(4)能正确地使用numpy生成一序列数据; (3分);

(5)程序有异常处理机制,无论如何输入都不会崩溃。(3分)

 

  1. 简易学生信息管理系统。

程序要求如下:

1、设计一个学生类,名为Student ,字段有姓名,年龄,成绩。

2、设计好display_records函数。用于显示所有学生信息。

3、设计好insert_record函数。它用于往数据库中插入一条学生记录。

4、程序运行后会有一个主循环,一般用while循环。它会不断地显示要求按1、2、3数字键,如果按其它的则提示输入错误。按1会显示所有学生信息,按2会往数据库中插入一条记录,按3中断循环。 以下是程序的参考结构:

答案:

 

评分标准:

(1)能够设计好Student类。(3分);

(2)能够正确地实例化一个Student类的对象。(3分);

(3)display_records函数能正确地显示所有学生信息。(3分);

(4)insert_record能正确地插入一条学生信息。(3分)  ;

(5)合理地运用了异常处理机制,程序无论如何输入都不会出错而崩溃。(3分)  ;

 

 

 

 

发表在 python | 标签为 | 留下评论

青少年软件编程(Python)等级考试试卷(五级)

青少年软件编程(Python)等级考试试卷(五级)

编写:李兴球

分数:100.00            题数:37

 

一、单选题(共25题,每题2分,共50分)

  1. 假设列表的名字叫lis,在里面有10只海龟对象。那么能让所有海龟前进10个单位的正确代码是?( )

 

A、[t.fd(10) for t in lis]

B、[t.fd(10) for t in range(len(lis))]

C、for turtle in lis:turtle.right(90)

D、while True: lis.fd(10)

 

  1. 以下代码输出哪些数字?( )

for i in range(10):

if i==5:continue

print(i,end=”)

A、1234678910

B、0123456789

C、012346789

D、0,1,2,3,4,5,6,7,8,9

 

  1. 哪个整数没有在以下代码执行的结果中。( )

for i in range(100,1000):

s = str(i)

if (int(s[0]) + int(s[-1]))==17:

print(i)

A、928

B、849

C、809

D、910

 

  1. 根据以下代码,以下哪种说法是正确的。( )

import random

s = set()

while True:

i = random.randint(1,10)

s.add(i)

if i==0:break

A、s是一个集合,它里面的数据会多于10个。

B、s是一个集合,它里面的数据最终会等于10个。

C、代码中的while循环执行次数是有限的。

D、s中的每个数据依次加入,所以s中的数据有序。

 

  1. 运行如下代码,结果是?( )

a = {32,76,8}

b = {1024,76,8}

print(a&b)

A、{8, 76,32,1024}

B、{8, 76}

C、{1024,32}

D、set()

 

 

根据以下代码,以下哪种描述是不正确的。( )

for i in range(10,1000):

gw = i%10

sw = i//10

if (gw+sw)**2 == i:

print(i)

A、81在程序的输出结果中

B、100在程序的输出结果中

C、23不在程序的输出结果中

D、程序执行了990次

 

 

  1. 下面代码运行后,以下哪种说法是正确的。( )

from turtle import *

a = list(map(str,[Turtle() for _ in range(5)]))

print(a)

A、a是一个列表,里面存储了5只海龟对象

B、运行代码后,只能看到一只海龟,所以并没有生成5只海龟对象。

C、for _ in range(5)是错误的for循环

D、a是一个列表,里面有5个字符串。

 

  1. 以下关于生成器的说法不正确的是。( )

A、生成器只是保存了生成数据的算法,本身不存储数据。

B、可以用next命令把生成器中的数据一个一个地生成出来。

C、for循环可以把生成器中的数据全部生成出来。

D、用for循环把生成器中的数据全部遍历后,还能无限次再遍历。

 

 

  1. 以下关于turtle模块,说法不正确的是( )

A、海龟模块是第三方模块,安装方法是pip install turtle

B、turtle模块是内置模块,不需要安装。

C、import turtle的意思是导入海龟模块

D、from turtle import * 意思 是从海龟模块导入所有命令或常量等

 

 

  1. “abc{:05d}efg”.format(6)执行后结果是什么?( )

A、’00006abcefg’

B、’abc6efg’

C、’abc          6efg’

D、’abc00006efg’

 

  1. 根据以下代码,s最有可能的数据类型是?( )

from turtle import Screen

sc = Screen()

s = sc._shapes

print(s.keys())

A、列表

B、元组

C、集合

D、字典

 

 

  1. 根据以下代码,以下选项中描述错误的是?( )

jihe = set(‘abcdefgggg’)

print(jihe[-1])

A、jihe是一个集合

B、set命令可以把字符串转换成一个集合。

C、jihe中的数据有10个

D、第二行代码是错误的

 

 

  1. python脚本程序可以用下列个模块打包成windows下的exe可执行程序?( )

A、pyinstaller

B、p2e

C、turtle

D、jieba

 

 

  1. 假设有两个坐标点分别是a=(3,4),b=(24,55)。下面哪个表达式不能求两点距离,假设导入了math模块。( )

 

A、((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5

B、math.dist(a,b)

C、power(((a[0]-b[0])**2 + (a[1]-b[1])**2),0.5)

D、math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)

 

  1. 以下代码运行后,输出的结果是?( )

>>> d = ‘1234567’

>>> sum(map(int,list(d[::-1]).pop() ))

A、1

B、28

C、7

D、0

 

 

  1. 关于以下代码,以下说法正确的是。( )

>>> import turtle

>>> cs = [‘red’,’orange’,’yellow’,’green’]

>>> turtle.color = cs

>>> turtle.fd(100)

>>> turtle.color(cs[0])

A、海龟的颜色最终变成了红色

B、海龟前进了100个单位

C、cs[-1]的结果是’red’

D、cs[0][0]的结果是’yellow’

 

  1. 下面哪个选项输出了11个换行符?( )

A、for i in range(11):print(‘\n’)

B、print(‘/n’*10)

C、print(‘\n’*11)

D、print(‘\r’*11)

 

 

  1. 下列代码说法不正确的是?( )

import time

while True:

s = str(time.time())

if (s[-1])==5:break

A、上面的while会在一定条件下结束,所以是一个有限循环

B、break可用于中断while循环

C、s不是一个字符串

D、时间模块的time.time()命令获取自1970年元月1号0点0分到现在的秒数

 

 

  1. 关于以下代码,说法正确的是:( )

>>> s = ‘\r\”\n’

>>> len(s)

A、s是一个非法字符串

B、len(s)的结果是3

C、len(s)的结果是6

D、s[-1]是’n’这个字符

 

 

  1. 下面代码绘制的图形是?( )

>>> from turtle import *

>>> ts = [Turtle(visible=False) for _ in range(4)]

>>> [ts[i].setheading(i*90) for i in range(4)]

>>> [t.fd(100) for t in ts]

A、正方形

B、三角形

C、十字架

D、圆形

 

 

  1. 关于以下程序,如果输入234,那么描述正确的是?( )

>>> list = [32,76,8,9,10]

>>> input = list[n]

>>> s = eval(input(‘请以半角逗号为分隔输入整数’))

>>> print(s)

A、s将会是一个整数

B、由于input被重新定义,所以s未定义

C、不能将列表赋值给list,因为list是关键词

D、根据Python特性,即使list被重新定义,它仍能新建列表

 

 

  1. 以下程序的文件名是turtle.py。根据它代码,描述正确的是?( )

import turtle

 

s = “””

import turtle

print(s)

“””

print(s)

exec(s)

 

A、程序会无限执行。

B、程序会执行很多次输出,但最终会由于递归错误而停止。

C、程序只会输出一些字符串,然后终止。

D、文件名是不能存储为turtle.py的。

 

 

 

  1. 执行下面代码,以下描述正确的是?(  )

for x in range(1,10,2):

b = set()

b.add(set())

 

A、b是一个集合,执行len(b)的结果是5。

B、b是一个集合,由于添加的都是空集合,所以最终b内只有一个对象

C、 由于每次循环b都是重新建立的一个空集合,只给它增加一个数据,所以执行len(b)结果是1。

D、 这是一个错误的程序

 

 

  1. 下面程序,以下选项中正确的是?( )

x = 10

f = 32

def f(a):

global x

return x + 10

 

print(str(f))

A、程序输出的结果是20

B、程序输出的结果是10

C、这是一个错误的程序

D、这个程序只是输出一个字符串

 

  1. 关于以下代码,输出结果是什么?( )

x = {key:value for key,value in zip(‘abcdefg’,’中华人民共和国’)}

lis = list(x)

print(”.join(lis))

 

A、[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]

B、abcdefg

C、[‘中’, ‘华’, ‘人’, ‘民’, ‘共’, ‘和’, ‘国’]

D、中华人民共和国

 

二、判断题(共10题,每题2分,共20分)

  1. 在代码 for _  in  range(100):pass 中 一个变量也没有,这是充许的。(    )

 

 

  1. s = ‘roblox’,然后执行s.split(),返回的也是一个字符串。( )

 

  1. 在Python计算机语言中,定义函数一定要用def开头,这是正确的。(  )

 

  1. 在Python中for循环实现重复执行一组语句的本质是迭代序列或散列中的数据给变量。(   )

 

  1. jieba模块中的lcut命令返回的是一个列表。( )

 

 

  1. 以下代码只会执行三次。(  )

while [32,76,8]:

[32,76,8].pop()

 

  1. 字符串的title和capitalize方法对于纯数字组成的字符串来说返回结果一样。( )

 

  1. 以下代码执行后a,b,c的值分别和x,y,z的值一样。(  )

import math

g = ( math.dist((0,0),(2,2)) for _ in range(3) )

a,b,c = g

x,y,z = g

 

  1. 运行如下,结果是55。 (    )

def fib(n): return 1 if n<=2 else fib(n-1) + fib(n-2)

print(sum(map(int,str(fib(10))) ))

 

  1. 为了让程序能正常运行,永远不崩溃,推荐用try…except…结构把程序全部包含在异常处理之中。( )

 

三、编程题(共2题,共30分)

  1. 显示词云图像

可以在海龟画图屏幕上把词云图像显示出来。下面是一段文本:

八十年代初期以来,食用菌栽培做为一项投资小、周期短、见效快的致富好项目在中国得以迅猛发展,食用菌产品曾一度供不应求,卖价不菲。食用菌产业是一项集经济效益、生态效益和社会效益于一体的短平快农村经济发展项目,食用菌又是一类有机、营养、保健的绿色食品。发展食用菌产业符合人们消费增长和农业可持续发展的需要,是农民快速致富的有效途径。有些国家还建成了年产鲜菇千吨以上的菇厂,还发展了既供观赏又供食品的家庭种菇和用菌丝体液体发酵生产食品添加剂的技术21世纪食用菌将发展成为人类主要的蛋白质食品之一2005年中国食用菌的总产量达1200万吨,居世界第一,据相关网站调查统计,2010年中国食用菌的总产量达2000万吨,占世界70%。由全禾菌业、九发集团等单位开发了食用菌液体菌种生产和工厂化栽培技术,大大提升了中国食用菌生产水平。食用菌产业已成为中国种植业中的一项重要产业。国内市场潜力巨大。因此,对国内市场要加大宣传力度及产业整合。

请把以上文本进行分词,把长度小于2的字符串去掉,然后用词云模块生成png图形,宽高是480×360,最后显示在Python海龟画图屏幕上,宽高是480×360。

 

 

评分标准:

(1)能够使用至少一种分词命令进行分词。(3分);

(2)能够把列表中的字符串长度小于2的去除。(3分);

(3)能够使用词云模块生成png图形。(3分);

(4)正确地设定海龟画图屏幕的宽高  ; (3分);

(5)能正确地把图片显示在海龟画图屏幕上。(3分)

 

  1. 海龟的切片操作。

程序要求如下:

1、程序会生成10只海龟,它们都放在一个列表中,比如列表的名字叫ts。

2、10只海龟会从左到右依次排开,比如,可以让它们每相隔50个单位。

3、程序需要合理地运用至少2个列表推导式,(硬凑的不算,下同)。

4、通过屏幕的textinput弹出对话框输入文本符号。文本中必需含有:号,即冒号,结果会对ts列表进行切片操作。如: screen.textinput(‘提示’,’请输入切片操作符号’)。

这个时候,输入1:4,则把索引为1,2,3的海龟隐藏并删除。输入[4:1:-1]则会把余下列表中的索引为4,3,2的海龟隐藏,并从ts列表中删除。(提示: 可用exec命令把字符串当成代码执行)。

5、要求在程序中合理地运用try…except…异常处理机制。

6、不断地重复输入,直到当所有海龟被隐藏及从ts列表中删除,最终ts列表为空,最后显示‘程序运行结束’几个大字。

答案:

 

评分标准:

(1)能够生成10只海龟,并一字排开。(2分);

(2)合理地运用了两个以上的列表推导式。(3分);

(3)运用了textinput进行输入。(2分)  ;

(4)合理地运用了异常处理机制。(3分)  ;

(5)海龟能按照输入的切片操作符正确地隐藏。(5分)  ;

 

 

 

 

发表在 python, 杂谈 | 标签为 | 留下评论

原创Python创意程序_全国青少年创意编程与智能设计_Python创意编程比赛

全国青少年创意编程与智能设计大赛参赛办法(Python创意编程比赛)
一、参赛对象
Python创意编程比赛设初中组和高中组。全省各地初中、高中(含中等职业学校)在校学生均以个人报名参加。
二、参赛形式
Python创意编程比赛分初评、复评和终评三个阶段,均以线上形式开展。每人限报1项作品,每项作品限1名指导教师。
2022年5月10日至6月10日,登录网址:(http://gsqskj.gsstm.org/indexMain点击进入)报名参赛。
三、作品类型
鼓励参赛者借助Python语言进行跨学科融合设计,作品类别如下
1.科学探索类:数学对象可视化、现实过程模拟仿真、科学实验等各学科的趣味性展示与探究。
2.实用工具类:有实用价值、能解决学习生活中的实际问题、提高学习工作效率的程序应用工具。
3.数字艺术类:通过程序生成和展示视觉艺术,具备创意、美感和互动性。
4.互动游戏类:各种竞技类、探险类、角色扮演类、球类、棋牌类游戏等。
四、作品要求
1.作品原创
作品可借鉴已有程序作品,但必须体现创作者的思考和创新。如作品程序代码与已存在第三方作品相似度在70%以上,且未标明借鉴来源或未能证明原创性,一律取消评奖资格。
2.艺术展现
作品充分展现计算机图形与计算机艺术特色,创意巧妙独特,表现形式丰富。作品合理运用图形与色彩,创造愉悦审美感受。
3.交互体验
作品的绘制过程流畅,富有创意。作品的交互设计简单明了,体验良好。作品内容主题清晰,易于理解。
4.程序技术
程序能够正常运行,运行过程稳定、流畅、高效,无明显错误;程序结构划分合理,代码编写规范,清晰易读;巧妙利用计算思维与算法,创造独特创意体验。
5.参赛作品的著作权归作者所有,使用权由作者与主办单位共享,主办单位有权出版、展示、宣传参赛作品。
五、作品申报
(一)在线提交Python创意编程作品。运行环境主要包括:
1.标准版Python 3.7和有限的第三方模块;
2.要求作品为纯Python代码实现,采用标准鼠标键盘交互,不需要特殊硬件辅助。
3.作品在标准版Python 3.7中运行,并与操作系统无关,不依赖网络在线资源。
4.除了Python标准发行版自带的内置模块(如Turtle、Tkinter等)之外,第三方模块仅限于:Numpy、Matplotlib、Jieba、Pillow、Pygame、Easygui。
(二)申报作品材料。主要包括:
1.作品效果图,即作品的关键画面截图,或作品运行效果的最终截图;效果图必须与程序实际运行结果一致。如作品生成有随机性效果,则文档中要充分说明随机设计的用意。
2.作品主题,包括:作品的名称,作品的创意设计说明,作品本身能体现出对主题的阐释,能够展现主题内涵或内容。目标描述不清晰或展示目的不明确的作品会被扣分。
3.编程技巧说明。充分描述作品中所运用的编码技巧、程序算法或工程设计方法,可运用恰当的逻辑流程图配合解释。
4.参考与引用说明。如果选手作品借鉴或参考了已有的第三方作品,选手应在说明文档中注明所借鉴参考的代码出处,并详细说明自己的创意或创新之处。如与原作相比未能展现出足够的创新,作品应被扣分。
5.拍摄作品阐述视频。内容包括创作思路、过程等,拍摄时长控制在2分钟以内,格式为MP4。

发表在 python, 杂谈 | 标签为 | 留下评论

中国空间站

李兴球Python turtle中国空间站

要求绘制中国空间站的题目,我在很短的时间就做好了,就是那个APO算法大赛要求的。以下是我写的源代码:

import random
import turtle as t

screen = t.getscreen()
screen.delay(0)
screen.bgcolor('black')
t.colormode(255)
t.speed(0)
t.pencolor('white')
t.penup()
for _ in range(200):
    x = random.randint(-500,500)
    y = random.randint(-500,500)
    t.goto(x,y)
    t.dot(random.randint(2,5))
t.goto(0,0)    
t.setheading(0)
t.color('blue')
t.begin_fill()
t.circle(-40)
t.end_fill()
t.pu()
t.goto(-60,-20)
t.right(40)
t.pd()
t.pencolor('yellow')
t.pensize(3)
t.circle(200,40)
t.circle(4,160)
t.right(15)
t.circle(250,8)
t.pu()
t.circle(250,18)
t.pd()
t.circle(250,5)
t.circle(4,160)
t.pu()
t.goto(-60,-60)
t.pd()
for i in range(5):
   t.fd(15)
   t.right(144)
t.pu()
t.goto(40,-80)
t.pd()
t.seth(-45)
t.pensize(2)
for i in range(5):
   t.fd(10)
   t.right(144)
t.pu()
t.goto(-40,-100)
t.pd()
t.circle(5)
t.pu()
t.goto(-10,-90)
t.pd()
t.circle(2)
t.pu()
t.goto(40,-10)
t.pd()
t.circle(10)
t.pu()
t.goto(65,8)
t.pd()
t.circle(6)
t.pu()
t.goto(-10,5)
t.pd()
t.circle(5)
t.hideturtle()

t.pencolor('magenta')
all_xy = []
xy_0 =  [(-76, 55), (-41, 88), (10, 32), (-24, 1), (-76, 55), (0, 0, 255)]
xy_0 = [list(cc) for cc in xy_0]
xy_0 = [(cc[0],cc[1] +300) for cc in xy_0[:-1]] + [(0, 0, 255)]

xy_1 =  [(34, 3), (87, -50), (48, -83), (1, -30), (34, 3), (0, 0, 255)]
xy_1 = [list(cc) for cc in xy_1]
xy_1 = [( cc[0],cc[1] +300) for cc in xy_1[:-1]]+  [(0, 0, 255)]

xy_2 =  [(27, 46), (42, 42), (50, 32), (53, 21), (-3, -29), (-3, -37), (-55, -84), (-67, -84), (-77, -79), (-83, -72), (-86, -55), (-80, -44), (-36, -4), (-24, -5), (27, 46), (192, 192, 192)]
xy_2 = [list(cc) for cc in xy_2]
xy_2 = [(cc[0],cc[1] +300) for cc in xy_2[:-1]]+  [(192, 192, 192)]

xy_3 =  [(-62, -29), (-30, -60), (-41, -70), (-74, -39), (-62, -29), (128, 64, 0)]
xy_3 = [list(cc) for cc in xy_3]
xy_3 = [(cc[0],cc[1] +300) for cc in xy_3[:-1]]+ [(128, 64, 0)]

xy_4 =  [(-40, -36), (-25, -20), (-15, -29), (-30, -46), (-40, -36), (255, 0, 0)]
xy_4 = [list(cc) for cc in xy_4]
xy_4 = [(cc[0],cc[1]+300) for cc in xy_4[:-1]] + [(0, 0, 255)]


all_xy.append(xy_0)
all_xy.append(xy_1)
all_xy.append(xy_2)
all_xy.append(xy_3)
all_xy.append(xy_4)

k = 2
for cors in all_xy:
    t.penup()
    x,y = cors[0]
    t.goto(x/k,y/k)
    t.pendown()
    if cors[-1]!='':
       t.fillcolor(cors[-1])
       t.begin_fill()
    for x,y in cors[1:-1]:
        t.goto(x/k,y/k)
    if cors[-1]!='':    
       t.end_fill()
        
t.pencolor('white')
t.penup()
t.goto(0,70)
t.write('中国空间站 ',align='center',font=('arail',26,'normal'))
    
t.done()

发表在 python, turtle | 标签为 | 留下评论

什么是Python生态编程

看了最新教育部2022年的计算机等级考试二级Python大纲,要掌握除了过程式编程,函数式编程,还有一个什么生态式编程。我就想,以前没有谁说过有这种编程方式呀。

我就进一步想了,原来Python有着庞大的计算生态,也就是说它有着异常丰富的第三方库。绝大多数你想实现的功能,别人已经实现了。你只要学会如何去找即可?去哪里找?当然是pypi.org。打开这个网站,它就像一个搜索引擎一样“只”提供一个搜索框框。让你自己去搜索想要的库。当然,也可以注册账号,上传自己的库。这样全世界的人都可以使用你的模块了。

所以,能掌握了相当一部分的库并且能快较学习新的库的使用方法,还能投入到产生实践中,从而有大量的产出,就意味着能创造更多的价值,这就叫Python生态编程。

为什么Python有这么庞大的第三方库而C语言等没有呢?这肯定和Python被设计的时候就确立了它的哲学有关。
感谢吉多·范·罗苏姆同志。当初他大概率也是不想到Python会发展到今天这样的有着庞大用户的计算机语言。

发表在 python, 杂谈 | 留下评论

看图编程之:九龟守空房

九龟守空房李兴球Python
这个程序的单元是定义一个画正方形的函数,以下是这个函数,其它代码自己组织即可:

import turtle

def draw_square(center,length,cc):
    """center:中心点坐标
       length:边长
       cc:填充颜色
       以center为中心点画边长为length的正方形
    """
    l2 = length/2
    turtle.goto(center)
    turtle.bk(l2)
    turtle.right(90)
    turtle.bk(l2)
    turtle.left(90)
    turtle.color(cc)
    turtle.begin_fill()
    for _ in range(4):
        turtle.fd(length)
        turtle.right(90)
    turtle.end_fill()
    turtle.right(90)
    turtle.fd(l2)
    turtle.left(90)
    turtle.fd(l2)

turtle.penup()
draw_square((-100,100),100,'red')

发表在 python, turtle | 留下评论

看图编程序练习之最胖十字架

下面这个图形不好取什么名字,先取这个名字吧,上课时把图形显示,让学生们去练习即可.
效果图最胖十字架

下面是参考程序:

import turtle

cs = ['red','orange','yellow','green']

turtle.shape('turtle')
turtle.bgcolor('black')
turtle.speed(0)
turtle.delay(0)

turtle.color('white')
turtle.penup()
turtle.begin_fill()
for i in range(4):
    turtle.fd(100)
    turtle.left(90)
turtle.end_fill()

for i in range(4):
    turtle.right(90)
    turtle.color(cs[i])
    turtle.begin_fill()
    turtle.circle(50,180)
    turtle.end_fill()

turtle.ht()

发表在 python, turtle | 留下评论

Python人脸识别器

这里是有一个GUI界面的人脸识别程序。以下程序需要相关库文件支持。李兴球Python人脸识别器


import face_recognition
from sprites import *
from PIL import Image

screen = Screen()
screen.setup(580,460)
root = screen._root
canvas = screen.getcanvas()
screen.bgcolor('light cyan')

t = Sprite('blank')

frame = TK.Frame(canvas)
frame.grid(row=0,column=1)          # 这里一定要用grid布局

# 标签
label = TK.Label(frame, text= "请", font= ('Helvetica 14 bold'))
label.grid(row=0,column=0)

联系微信scratch8,成为会员,可以查看以下源代码:

成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

发表在 python | 标签为 | 留下评论

今天上午我们一节Python课的题目的三个解法

"""
寻找四位数..py
这个四位数各位上的数字的四次方之和等于本身的数,
"""
for x in range(1000,10000):
    # 拆x为4个数字,a,b,c,d
    y = str(x)
    d = int(y[0])
    c = int(y[1])
    b = int(y[2])
    a = int(y[3])
    if a**4 + b*b*b*b + c*c*c*c + d*d*d*d ==x:
       print(x)

# 枚举个十百千的合成法
for d in range(1,10):
    for c in range(10):
        for b in range(10):
            for a in range(10):
                x = d*1000 + c*100 + b*10 + a
                if d**4+c**4+b**4+a**4==x:
                    print(x)

"""
寻找四位数..py
这个四位数各位上的数字的四次方之和等于本身的数,
"""
for x in range(1000,10000):
    # 拆x为4个数字,a,b,c,d
    y = x
    d = y%10
 
    y = y // 10
    c = y%10
     
    y = y//10
    b = y%10
     
    y = y//10
    a = y%10

    if a**4 + b*b*b*b + c*c*c*c + d*d*d*d ==x:
       print(x)


发表在 python | 标签为 | 留下评论

turtle绘的正态分布图.py

李兴球Python之turtle normal distribute正态分布图

“””
turtle绘的正态分布图.py
“””
import turtle
import numpy as np

datas = [int(np.random.randn()*100) for _ in range(50000)]

print(min(datas))
print(max(datas))
counts = {}
for c in range(min(datas),max(datas)+1):
freq = datas.count(c) # 每个数产生的次数
counts[c] = freq # 放在字典中,如counts[3]=50,记录了3有50个

turtle.delay(0)
turtle.speed(0)
turtle.penup()
for key,value in counts.items():
turtle.goto(key,value)
turtle.dot(4)

turtle.done()

发表在 python, turtle | 留下评论

看到有人画的Python for循环流程图不对, 无法零容忍,所以做了一个

李兴球for循环机制流程图
进入青少年Python的QQ群本来想下载5,6级课件的,找了一圈没找到,问宋顺南老师才知道还未公开,无意中下载到祝莹的PPT,看了一下,感觉里面的for循环流程图有问题,于是自己制了一个。
李兴球Python的for循环机制流程图
宋顺南

发表在 python, 杂谈 | 留下评论

自制弹出输入框测试程序.py

"""
   自制弹出输入框测试程序.py 这是一个研究如何自制弹出输入框的测试程序,
   (由于对turtle的textinput命令不满意)
"""
from tkinter import *
import sys

class popupWindow:
    def __init__(self,master):
        top=self.top=Toplevel(master)
        top.withdraw()
        m_x = master.winfo_rootx()
        m_y = master.winfo_rooty()
        p_width= master.winfo_reqwidth()
        p_height= master.winfo_reqheight()
        s_width= self.top.winfo_reqwidth()
        s_height= self.top.winfo_reqheight()
        
        print('master.winfo_rootx=',m_x)
        print('master.winfo_rooty=',m_y)
        
        print('p_width=',p_width)
        print('p_height=',p_height)
        print('s_width=',s_width)
        print('s_height=',s_height)
        width = p_width//3
        height = 60
        self.top.geometry("%dx%d+%d+%d" % (p_width//3,60,master.winfo_rootx()+(p_width-width)//2,
                                      master.winfo_rooty()+p_height - height*2))
        self.l=Label(top,text="请输入文本:")
        self.l.pack()
        self.e=Entry(top,width=p_width//24)
        self.e.pack()
        self.b=Button(top,text=' 确  定 ', command=self.cleanup)
        self.b.pack()
        self.top.deiconify()  #显示
        
    def cleanup(self):
        self.value=self.e.get()
        self.top.destroy()

class mainWindow(object):
    def __init__(self,master):
        self.master=master
        self.b=Button(master,text="click me!",command=self.popup)
        self.b.pack()
        self.b2=Button(master,text="print value",command=lambda: sys.stdout.write(self.entryValue()+'\n'))
        self.b2.pack()

    def popup(self):
        self.w=popupWindow(self.master)
        self.b["state"] = "disabled" 
        self.master.wait_window(self.w.top)
        self.b["state"] = "normal"

    def entryValue(self):
        return self.w.value


if __name__ == "__main__":
    root=Tk()
    c = Canvas(width=800,height=600,bg='yellow')
    c.pack()
    m=mainWindow(root)
    root.mainloop()

发表在 python, tkinter | 留下评论

鼠标指针跟随海龟多线程版

以前编写的程序是海龟跟随鼠标指针,现在倒过来了,这是利用事件产生方法实现的。

import time
import turtle
from threading import Thread

def mouse_follow_turtle(test_turtle):
    root = test_turtle.getscreen()._root    
    while True:        
        left = test_turtle.xcor() + 400
        top = 300 - test_turtle.ycor()
        root.event_generate("",warp=True,x=left,y=top)
        time.sleep(0.1)
        
def turtle_move(test_turtle):
     while True:
        test_turtle.fd(1)
        test_turtle.left(1)
        
if __name__ == '__main__':
    
    turtle.setup(800,600)
    tom = turtle.Turtle('turtle')
    t1 = Thread(target=mouse_follow_turtle,args=(tom,))
    #t1.setDaemon(True)
    t1.start()
    t2 = Thread(target=turtle_move,args=(tom,))
    #t2.setDaemon(True)
    t2.start()   

    turtle.mainloop()
        


发表在 python, turtle | 留下评论

海龟移动事件产生测试程序_root.event_generate

"""
   海龟移动事件产生测试程序_root.event_generate
   turtle基于tkinter,所以调用root的event_generate能指挥鼠标移动,当然按键等都可以,
   这样的海龟编程可是有趣多了,潘朵拉盒子打开了,会一发不可收拾。
   这个程序在运行后,海龟会随机移动,然后鼠标指针过一会儿会瞄准它,让它消失!
   由于速度太快,所以录的gif看不出来。示例为硬编码,只为学习,没搞太抽象。
"""
import random
import turtle

def mouse_pos():
    """获取相对于海龟屏幕的鼠标指针坐标,和屏幕的缩放参数scale无关。"""      
    abs_coord_x = root.winfo_pointerx() - root.winfo_rootx()
    abs_coord_y = root.winfo_pointery() - root.winfo_rooty()
    x =  abs_coord_x - 400         # 减去屏幕宽度一半
    y =  300 - abs_coord_y
    x, y = (x-3),(y+3) 
    return (x,y)

def die():
    if turtle.fillcolor()!='red':
       turtle.fillcolor('red')
       turtle.ontimer(die,100)
    else:
        turtle.ht()

def wait():
    # 获取鼠标指针在画布上的坐标(基于海龟坐标系)
    mx,my = mouse_pos()
    if ((mx-turtle.xcor())**2 + (my-turtle.ycor())**2)**0.5>10:
        turtle.ontimer(wait,100)
    else:
        die()

    
turtle.setup(800,600)
turtle.shape('turtle')
turtle.shapesize(2)
cv = turtle.getcanvas()
root = turtle.getscreen()._root

while 1:
    turtle.seth(random.randint(1,360))
    turtle.fd(random.randint(10,100))
    if random.randint(1,20)==1:
      left = turtle.xcor()  + 400
      top = 300 - turtle.ycor()
      root.event_generate('', warp=True, x=left, y=top)
      wait()
      break


发表在 python, tkinter, turtle | 标签为 , | 留下评论

反转算法演示程序.py

李兴球Python反转算法演示程序

"""
   反转算法演示程序.py
"""
from sprites import *
from random import randint

screen = Screen()
screen.delay(10)

w = Sprite('blank')
w.color('gray84')
w.sety(50)
w.write('反转算法演示程序',align='center',font=('黑体',34))

digits = [randint(0,1000) for _ in range(randint(5,10))]
names = [f'res/_{d}.png' for d in digits]
[txt2image(str(d),filename,fontsize=22 ) for d,filename in zip(digits,names)]
n = len(digits)                    # 角色数量 
x = -(n-1)*70/2                    # 最左边角色的x坐标
numbers = []
for i in range(n):
    p = Sprite(names[i],pos=(x,220))
    p.stamp()
    p.speed(1)
    numbers.append(p)
    x = x + 70
[p.sety(0) for p in numbers]

i = 0
j = n-1
while i
							
发表在 python, sprites | 标签为 | 留下评论

幽默的随机选择.py random.choice命令演示程序

李兴球Python幽默的随机选择

"""
幽默的随机选择.py
random.choice命令演示程序
"""
import random
from sprites import *

screen = Screen()
screen.setup(640,780)

cats = []
for i in range(10):
    x = -120
    y = 300 - i * 70
    cats.append(Sprite(2,pos=(x,y)))

b = Sprite(6)
b.rotatemode(1)
b.right(180)
b.bk(100)
b.wait(1)
b.say('random.choice命令演示程序',delay=4)
b.say('现在开始')
b.say('想去抓老鼠的站出来!')

screen.delay(2)
被选择的猫 = random.choice(cats)
 
for cat in cats:
    if cat == 被选择的猫:continue
    cat.speed(1)
    cat.bk(100)
cat.wait(1)

被选择的猫.say('咦,其它猫呢?')
b.say('你站出来了,就你了!')
被选择的猫.say('蝶妹,我冤枉啊')
b.say('猫哥,你应该感到幸福!')

screen.mainloop()

发表在 python, sprites | 标签为 | 留下评论

修改线条端点风格和拐弯样式_joinstyle和capstyle

李兴球Python capstyle 和joinstyle端点风格

"""
  修改线条端点风格和拐弯样多_joinstyle和capstyle,
  有人问我如何修改线条的端点风格,这就是一个tkinter的问题,
  不过,还是要研究turtle模块才能把代码写出来,
  下面的代码演示了如何修改,顺便还有连接风格,
  所有代码如下所示:
"""
import turtle

turtle.pensize(10)
cv = turtle.getcanvas()
t = turtle.getturtle()
lid = t.currentLineItem
cv.itemconfig(lid,capstyle=turtle.TK.BUTT,
              joinstyle=turtle.TK.MITER)
t.fd(100)

t.goto(100,100)
for _ in range(4):
    turtle.fd(100)
    turtle.right(90)

参考文章: https://www.pythonstudio.us/tkinter-reference/cap-and-join-styles.html

发表在 python, tkinter, turtle | 留下评论