turtle fillcolor_没有人比我更懂turtle!

    大家在初学的时候肯定听说过python有内置一个叫turtle的画图库,他因为笔的形状是一只海龟而得名8f3e751099566f2186882ecb55f0b79f.png

41a0e8002697ad561a5f5387186a2302.png

a47b236f0110db8508d46ad9059d34b2.png

    今天我在翻python库源码的时候,无意间发现了一个包,这时候,我想要大喊一声:

    没有人比我更懂turtle!

/1.turtle库简介/

    这里为了一些小白还没有听说过turtle,先简介一下:

        Turtle库是Python语言中一个很流行的绘制图像的函数库。

    嗯,结束了d0d15f05cb95fbf89f81b77e133f506d.png

/2.turtledemo/

    接下来就要给大家讲讲我发现那个包了,这个包名叫turtledemo,顾名思义,就是python官方给与的turtle库实例。

    我数了一下,有整整19个项目e515af31e181641bdbdfebb7a317cc16.png

b41682f25d2870b488116df5ae38faa3.png

    我们挑其中几个特别突出的项目来说一下:

/3.minimal_hanoi/

    我们直接导入就可以运行了:

import turtledemo.minimal_hanoi as tmtm.main()

    运行后是一个汉诺塔动画,单击空格开始:

1376b130df7a410a2c1c64c51d0b31a5.png

    单击空格后:

1e7ef7f79c17ea6c1e612efef7ee7c84.png

    他会可视化的执行移动汉诺塔的过程,代码如下:

from turtle import *class Disc(Turtle):    def __init__(self, n):        Turtle.__init__(self, shape="square", visible=False)        self.pu()        self.shapesize(1.5, n*1.5, 2) # square-->rectangle        self.fillcolor(n/6., 0, 1-n/6.)        self.st()class Tower(list):    "Hanoi tower, a subclass of built-in type list"    def __init__(self, x):        "create an empty tower. x is x-position of peg"        self.x = x    def push(self, d):        d.setx(self.x)        d.sety(-150+34*len(self))        self.append(d)    def pop(self):        d = list.pop(self)        d.sety(150)        return ddef hanoi(n, from_, with_, to_):    if n > 0:        hanoi(n-1, from_, to_, with_)        to_.push(from_.pop())        hanoi(n-1, with_, from_, to_)def play():    onkey(None,"space")    clear()    try:        hanoi(6, t1, t2, t3)        write("press STOP button to exit",              align="center", font=("Courier", 16, "bold"))    except Terminator:        pass  # turtledemo user pressed STOPdef main():    global t1, t2, t3    ht(); penup(); goto(0, -225)   # writer turtle    t1 = Tower(-250)    t2 = Tower(0)    t3 = Tower(250)    # make tower of 6 discs    for i in range(6,0,-1):        t1.push(Disc(i))    # prepare spartanic user interface ;-)    write("press spacebar to start game",          align="center", font=("Courier", 16, "bold"))    onkey(play, "space")    listen()    return "EVENTLOOP"if __name__=="__main__":    msg = main()    print(msg)    mainloop()

/4.sorting_animate/

    这个是真的厉害,它可视化还原了三个常用排序算法(快速排序,插入排序,选择排序):

72fe1cfcdb57b86a874f0a083f505550.png

    按下i是插入排序,s是选择排序,q是快速排序,r随机打乱(下面示范q):

b7ca0e5ba0cd586bf2a3bcdbbf599f81.png

    一个一个选定基准值,一个一个比较,几次过后排序完成。

    代码如下:

from turtle import *import randomclass Block(Turtle):    def __init__(self, size):        self.size = size        Turtle.__init__(self, shape="square", visible=False)        self.pu()        self.shapesize(size * 1.5, 1.5, 2) # square-->rectangle        self.fillcolor("black")        self.st()    def glow(self):        self.fillcolor("red")    def unglow(self):        self.fillcolor("black")    def __repr__(self):        return "Block size: {0}".format(self.size)class Shelf(list):    def __init__(self, y):        "create a shelf. y is y-position of first block"        self.y = y        self.x = -150    def push(self, d):        width, _, _ = d.shapesize()        # align blocks by the bottom edge        y_offset = width / 2 * 20        d.sety(self.y + y_offset)        d.setx(self.x + 34 * len(self))        self.append(d)    def _close_gap_from_i(self, i):        for b in self[i:]:            xpos, _ = b.pos()            b.setx(xpos - 34)    def _open_gap_from_i(self, i):        for b in self[i:]:            xpos, _ = b.pos()            b.setx(xpos + 34)    def pop(self, key):        b = list.pop(self, key)        b.glow()        b.sety(200)        self._close_gap_from_i(key)        return b    def insert(self, key, b):        self._open_gap_from_i(key)        list.insert(self, key, b)        b.setx(self.x + 34 * key)        width, _, _ = b.shapesize()        # align blocks by the bottom edge        y_offset = width / 2 * 20        b.sety(self.y + y_offset)        b.unglow()def isort(shelf):    length = len(shelf)    for i in range(1, length):        hole = i        while hole > 0 and shelf[i].size < shelf[hole - 1].size:            hole = hole - 1        shelf.insert(hole, shelf.pop(i))    returndef ssort(shelf):    length = len(shelf)    for j in range(0, length - 1):        imin = j        for i in range(j + 1, length):            if shelf[i].size < shelf[imin].size:                imin = i        if imin != j:            shelf.insert(j, shelf.pop(imin))def partition(shelf, left, right, pivot_index):    pivot = shelf[pivot_index]    shelf.insert(right, shelf.pop(pivot_index))    store_index = left    for i in range(left, right): # range is non-inclusive of ending value        if shelf[i].size < pivot.size:            shelf.insert(store_index, shelf.pop(i))            store_index = store_index + 1    shelf.insert(store_index, shelf.pop(right)) # move pivot to correct position    return store_indexdef qsort(shelf, left, right):    if left < right:        pivot_index = left        pivot_new_index = partition(shelf, left, right, pivot_index)        qsort(shelf, left, pivot_new_index - 1)        qsort(shelf, pivot_new_index + 1, right)def randomize():    disable_keys()    clear()    target = list(range(10))    random.shuffle(target)    for i, t in enumerate(target):        for j in range(i, len(s)):            if s[j].size == t + 1:                s.insert(i, s.pop(j))    show_text(instructions1)    show_text(instructions2, line=1)    enable_keys()def show_text(text, line=0):    line = 20 * line    goto(0,-250 - line)    write(text, align="center", font=("Courier", 16, "bold"))def start_ssort():    disable_keys()    clear()    show_text("Selection Sort")    ssort(s)    clear()    show_text(instructions1)    show_text(instructions2, line=1)    enable_keys()def start_isort():    disable_keys()    clear()    show_text("Insertion Sort")    isort(s)    clear()    show_text(instructions1)    show_text(instructions2, line=1)    enable_keys()def start_qsort():    disable_keys()    clear()    show_text("Quicksort")    qsort(s, 0, len(s) - 1)    clear()    show_text(instructions1)    show_text(instructions2, line=1)    enable_keys()def init_shelf():    global s    s = Shelf(-200)    vals = (4, 2, 8, 9, 1, 5, 10, 3, 7, 6)    for i in vals:        s.push(Block(i))def disable_keys():    onkey(None, "s")    onkey(None, "i")    onkey(None, "q")    onkey(None, "r")def enable_keys():    onkey(start_isort, "i")    onkey(start_ssort, "s")    onkey(start_qsort, "q")    onkey(randomize, "r")    onkey(bye, "space")def main():    getscreen().clearscreen()    ht(); penup()    init_shelf()    show_text(instructions1)    show_text(instructions2, line=1)    enable_keys()    listen()    return "EVENTLOOP"instructions1 = "press i for insertion sort, s for selection sort, q for quicksort"instructions2 = "spacebar to quit, r to randomize"if __name__=="__main__":    msg = main()    mainloop()

/5.colormixer/

    这个项目可以与用户互动,类似tk的colorchooser:

8b156476879ea714c39dae03ff9fd7d9.png

    拖动后:

6c412f121e34af0fb6c80bf0c0546a96.png

    源代码:

from turtle import Screen, Turtle, mainloopclass ColorTurtle(Turtle):    def __init__(self, x, y):        Turtle.__init__(self)        self.shape("turtle")        self.resizemode("user")        self.shapesize(3,3,5)        self.pensize(10)        self._color = [0,0,0]        self.x = x        self._color[x] = y        self.color(self._color)        self.speed(0)        self.left(90)        self.pu()        self.goto(x,0)        self.pd()        self.sety(1)        self.pu()        self.sety(y)        self.pencolor("gray25")        self.ondrag(self.shift)    def shift(self, x, y):        self.sety(max(0,min(y,1)))        self._color[self.x] = self.ycor()        self.fillcolor(self._color)        setbgcolor()def setbgcolor():    screen.bgcolor(red.ycor(), green.ycor(), blue.ycor())def main():    global screen, red, green, blue    screen = Screen()    screen.delay(0)    screen.setworldcoordinates(-1, -0.3, 3, 1.3)    red = ColorTurtle(0, .5)    green = ColorTurtle(1, .5)    blue = ColorTurtle(2, .5)    setbgcolor()    writer = Turtle()    writer.ht()    writer.pu()    writer.goto(1,1.15)    writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))    return "EVENTLOOP"if __name__ == "__main__":    msg = main()    print(msg)    mainloop()

/6.视觉类作品/

    这类的优秀作品有很多,就一起来看下吧:

    rosette.py:

82a61af78816c0fbbc483c82a64c1b46.png

    round_dance.py:    

4b0aeab4b6a64e17cbc62bc349c0d4cc.png

    bytedesign.py:

e29aa95ac77fa828c55a3ec802827a5b.png

/7.实用技术/

    还有一些炫技类的项目:

    clock.py:

ea077c525e11a873c8bf78088fbd52a9.png

    two_canvases.py(两个画布):

6cabd5ccdb97b2cee3163775eba6f799.png

    yinyang.py:

05cb258da445d9ff4218d981258126b3.png

    今天你视觉盛宴了吗5ecba2baee4ede7d393e93c82e491ca3.png178df83c21c825bc03b514cafce8dcb0.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值