資源簡介 (共72張PPT)初級編程并非所有的蛇都會爬行第一章 開始PYTHON學習你將了解什么是python在計算機上安裝并使用python1.Python介紹一種計算機語言高級語言(Java,Vb,Ruby,Python,C等多達上百種)PYTHON學習和人類一樣,計算機使用多種語言進行交流。一個編程語言只是一種與計算機對話的特殊方式。人類和計算機都能理解的指令。2.安裝Python-1獲取安裝程序(下載)https://www.python.org/downloads/windows/注意根據操作系統選擇下載64或32位版本(可執行文件)在windows下執行安裝程序PYTHON學習2.安裝Python-2啟動python shell(IDLE)PYTHON學習這就是Python ShellPython Shell就是在計算機上解釋執行python語言的控制臺。相當于你的大腦負責解釋你和別人所說的話,并按照要求進行動作。3.和計算機交流吧你告訴計算機的第一句話>>>print("Hello World")HelloWorld>>>PYTHON學習讓計算機做幾道數學題>>> 3 * 52156>>>3670 - 1563514Symbol Operation+Addition(加)-Subtraction(減)*Multiplication(乘)/Division(除)第二章 編程第一步(變量)PYTHON學習你將了解什么是變量?它能干什么?如何使用它4.什么是變量變量(variable)編程中的變量描述了存儲信息的地方。比如數字、文本、數字和文本等等。從另一方面看,變量就像一個標簽。PYTHON學習>>> fred =100#定義一個變量,并給變量賦值>>> print(fred)#告訴計算機把變量表示的內容顯示出來100>>> fred =200#定義一個變量,并給變量賦值>>> john =fred#定義另一個變量,并把fred的值賦值給它>>> print(john)200>>> found_coins = 20>>> magic_coins = 10>>> stolen_coins = 3>>> found_coins + magic_coins * 2 - stolen_coins * 331第三章 編程第二步(常用數據)PYTHON學習你將了解STRINGS -----字符串LISTS -----列表TUPLES -----元組MAPS -----地圖1.字符串StringString(字符串)在編程術語中,我們通常稱文本為字符串。你可以把一個字符串看作字母的集合,本資料里所有的字母、數字和符號都是一串字符。PYTHON學習>>> fred = 'What is pink and fluffy Pink fluff!!'>>> print(fred)What is pink and fluffy Pink fluff!!創造一個字符串,把它放在變量里,讓計算機顯示出來說明字符串用”或者‘來定義字符串轉義符號\ ,試著頂一個I’AM COMPUTER1.字符串String在字符串種嵌入值PYTHON學習>>> myscore = 1000>>> message = 'I scored %s points'>>> print(message % myscore)I scored 1000 points>>> nums = 'What did the number %s say to the number %s Nice belt!!'>>> print(nums % (0, 8))What did the number 0 say to the number 8 Nice belt!!字符串乘法>>> print(10 * 'a')Aaaaaaaaaa試試下面的輸出結果spaces= ' ' * 25print('%s 12 Butts Wynd' % spaces)2.比字符串更強大的列表(list)LIST(列表)很多變量的集合,用[]進行定義PYTHON學習>>> some_numbers = [1, 2, 5, 10, 20]>>> some_strings= ['Which', 'Witch', 'Is', 'Which']定義一個list你可以對list進行如下操作>>> some_some_strings.append(‘bear burp’)#追加項目>>>delsome_strings[2] #刪除第3項>>>print(some_strings[2:3])#顯示第3-4項>>>print(some_strings)#顯示所有項>>>print(some_numbers+some_strings) #可以做加法>>>print(some_numbers* 5) #可以做乘法除法,減法不行哦!考慮一下為什么2.另一種列表元祖(tuples)TUPLE(元祖)元組類似于使用圓括號的列表,用()進行定義,區別是創建后不能更改PYTHON學習>>> fibs = (0, 1, 1, 2, 3)>>> print(fibs[3])定義一個tuple你不可以改變tuple的內容否則計算機給給你報錯>>> fibs[0] = 4Traceback (most recent call last):File "<pyshell>", line 1, in <module>fibs[0] = 4TypeError: 'tuple' object does not support itemassignment2.幫你找到你想要的(字典)MAP(字典)字典中的每一項都有一個鍵和一個對應的值。你可以根據鍵找到值。PYTHON學習>>> favorite_sports = {'Ralph Williams' : 'Football','MichaelTippett':'Basketball','Edward Elgar' : 'Baseball','RebeccaClarke' : 'Netball','EthelSmyth' : 'Badminton','Frank Bridge' : 'Rugby'}定義一個map你可以對字典做如下操作>>> print(favorite_sports[‘Rebecca Clarke’])#找到RebeccaClarke喜歡的運動>>>delfavorite_sports[‘Ethel Smyth’] #從字典中刪除EthelSmyth數據>>>favorite_sports[‘Ethel Smyth’]=‘Ice Hockey‘ #修改Ethel Smyth喜歡的運動>>>favorite_sports[‘Can Can’]=‘tennis’ #追加cancan喜歡的項目第四章 海龜畫圖PYTHON學習你可以畫出絢麗的圖案1.什么是海龜PYTHON學習Turbles是一個畫板模塊,你可以利用它繪圖。正如你寫字并不需要你去制造鉛筆和紙張,你可以利用turtle去繪畫2.海龜繪圖PYTHON學習import turtle #引進海龜,你可以開始使用它turtle.pencolor("red") #設置畫筆顏色(紅色)turtle.pensize(1) #設置畫筆粗細turtle.forward(100) #讓海龜前進50個像素turtle.left(90) #左轉90度turtle.forward(100) #讓海龜繼續前進50個像素turtle.left(90) #左轉90度turtle.forward(100) #讓海龜繼續前進50個像素turtle.left(90) #左轉90度turtle.forward(100) #讓海龜繼續前進50個像素turtle.up() #讓海龜抬起筆turtle.left(90) #左轉90度turtle.forward(50) #讓海龜繼續前進25個像素turtle.down() #讓海龜放下筆turtle.pencolor("green") #設置畫筆顏色(綠色)turtle.pensize(3) #設置畫筆粗細turtle.circle(50) #畫一個半徑50的圓3.運用技巧PYTHON學習import turtle #引進海龜,你可以開始使用它myColor=["red","green","brown"]index =0forx in range(250):turtle.pencolor(myColor[index])index +=1if index == 3:index = 0turtle.forward(x*2)turtle.left(92)右邊的圖怎么畫出來的?看看下面的代碼讓計算機干了什么第五章 邏輯判斷PYTHON學習用IF ELSE判斷邏輯1.邏輯判斷PYTHON學習age = 10if age>= 20:print("oh!you are yong")Elif age >20 and age < 50print("oh!you areold")else:print("oh!you aretoo old")2.邏輯判斷結構PYTHON學習條件符號邏輯塊3.多條件的邏輯判斷PYTHON學習if age >= 10 and age <= 13:多個條件同時滿足任何一個條件滿足即可if age == 10 or age == 11 or age == 12 or age == 13:復合型條件ifsex ==“femal” and (age== 10 or age == 11 or age == 12 or age ==13):4.類型轉換PYTHON學習>>> myval = None>>> if myval == None:print("The variable myval doesn't have a value")什么都沒有保存的空值>>>age=10>>> ifage==10:print("The variable myval doesn't have a value")數值是字符串還是數字???>>>age=’10’>>> ifage==10:print("The variable myval doesn't have a value")>>> age = '10'>>> converted_age = int(age)>>> age = 10>>> converted_age = str(age)>>> age ='10.5'>>> converted_age = int(age)>>>ifage==10:print("The variable myval doesn't have a value")結果如何第六章 重復事件處理PYTHON學習1.循環PYTHON學習作業要抄寫100遍???NO!print(“homework”)print(“homework”)print(“homework”)print(“homework”)print(“homework”)print(“homework”)print(“homework”)print(“homework”)print(“homework”)…………..print(“homework”)print(“homework”)print(“homework”)print(“homework”)soeasy!!for x in range(0,99):print(‘homework')for x in range(0,99):print('hello %s' % x)試試這個2.列表(list)的循環PYTHON學習>>> print(list(range(10, 20)))[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]簡單的列表打印class_list = ["class1","class2","class3","class4","class5"]for x in range(0,4):print('hello %s' %class_list[x])①循環方式的列表打印②循環方式的遍歷列表>>> wizard_list = ['spider legs', 'toe of frog', 'snail tongue','bat wing', 'slug butter', 'bear burp']>>> for i in wizard_list:print(i)左邊的1和2實現方式有什么區別?hugehairypants= ['huge', 'hairy', 'pants']fori in hugehairypants:print(i)forj in hugehairypants:print(j)推測一下下面的結果3.一道循環的計算題PYTHON學習問題寶箱里有20枚金幣,每天會增加10枚,但是烏鴉每周會偷走3枚,請計算一年53周每周寶箱內會剩余多少金幣>>> found_coins = 20>>> magic_coins = 70>>> stolen_coins = 3u >>> coins = found_coinsv >>> for week in range(1, 53):w coins = coins + magic_coins - stolen_coinsx print('Week %s = %s' % (week, coins))4.循環處理的幾種語法PYTHON學習forstep in range(0, 20):print(step)FOR循環x= 45y= 80whilex < 50 and y < 100:x= x + 1y= y + 1print(x, y)WHILE循環forx in range(0, 20):print('hello %s' % x)ifx < 9:breakBreak可以提前退出循環第七章 模塊和函數PYTHON學習函數是一些處理邏輯的集合模塊是函數,變量的集合擁有更強大的功能海龜就是一個繪圖模塊1.函數構成PYTHON學習deftestfunc(myname):print('hello %s' % myname)函數名,參數,處理testfunc('Mary')print(savings(10, 10, 5))執行函數deftestfunc(fname, lname):print('Hello %s %s' % (fname, lname))函數可以有多個參數函數可以有返回值def savings(pocket_money, paper_route, spending):returnpocket_money + paper_route – spending2.一個函數的例子PYTHON學習每周生產X個罐子,計算出一年中每周位置總共生產的罐子。def spaceship_building(cans):total_cans= 0forweek in range(1, 53):total_cans= total_cans + cansprint('Week %s = %s cans' % (week, total_cans))函數調用spaceship_building(2) #A工廠每周只能生產2個spaceship_building(10) #B工廠每周只能生產10個考慮一下使用函數的好處PYTHON學習3.模塊(moudle)如何導入模塊importsys#導入系統模塊Import turtle#導入海龜繪圖模塊只有導入模塊后,才可以使用它PYTHON學習4.使用sys模塊sys模塊內部有一個特殊的對象稱為stdin(標準輸入),它提供了一個相當有用的函數readline。ReadLine函數用于讀取一行文本類型在鍵盤上,直到按回車鍵。Standardinput的略稱importsysdef ageEV():print('How old are you ')age = int(sys.stdin.readline())if age <= 15:print('you are a child!')elif age >15 and age<40:print('you are a young!')else:print('you are old!')ageEV()第八章使用類和對象PYTHON學習一切皆對象對象的定義被稱作類PYTHON學習1.類的實際概念PYTHON學習2.類的實際概念-2主類class Things:passThings為類名,pass表示類里面為空如果東西為父類的一部分,那么可以定義為子類Class Inanimate(Things):passInanimate為類名,括號中的Things表示父類classAnimate(Things):pass同樣我們可以定義東西的另一個子類—生物可以接著往下定義其他子類class Sidewalks(Inanimate):pass定義無生命東西的子類—人行道以此類推classAnimals(Animate):passclassMammals(Animals):passclassGiraffes(Mammals):passPYTHON學習3.類的使用classGiraffes(Mammals):pass你有一只長頸鹿,我們給它名字叫reginald(對象)reginald = Giraffes()定義了長頸鹿類對象的使用你的類定義空空如野,嘗試加些特征(函數)吧classAnimals(Animate):defbreathe(self): #呼吸passdefmove(self):#移動passdefeat_food(self):#食物passclass Mammals(Animals):deffeed_young_with_milk(self):passclass Giraffes(Mammals):defeat_leaves_from_trees(self):passPYTHON學習4.為什么要使用類和對象reginald = Giraffes() #名字為reginald的長頸鹿對象reginald.move()#讓長頸鹿reginald移動reginald.eat_leaves_from_trees()#讓長頸鹿reginald吃樹葉你有一只長頸鹿,我們給它名字叫reginaldharold= Giraffes() #名字為harold的長頸鹿對象reginald.move()#讓長頸鹿harold移動思考reginald.move()為什么長頸鹿可以調用move()函數進行移動子類繼承父類的函數以及屬性PYTHON學習5.類和對象的例子class Animals(Animate):defbreathe(self):print('breathing')defmove(self):print('moving')defeat_food(self):print('eating food')class Mammals(Animals):deffeed_young_with_milk(self):print('feeding young')class Giraffes(Mammals):defeat_leaves_from_trees(self):print('eating leaves')reginald = Giraffes()harold = Giraffes()reginald.move()harold.eat_leaves_from_trees()豐富你的類使用你的類和對象類的函數都有一個參數叫self,它是干什么的?PYTHON學習6. Self的作用class Giraffes(Mammals):deffind_food(self):self.move()print("I've found food!")self.eat_food()defeat_leaves_from_trees(self):self.eat_food()defdance_a_jig(self):self.move()self.move()self.move()self.move()Self代表類自己的對象調用函數時這個參數不是必須的一個函數可以調用另外一個函數PYTHON學習6.類的特殊函數__self__()__self__()是一個特殊函數,它在定義對象時被調用,用于通過傳遞參數初期化一些對象的屬性class Giraffes:def__init__(self, spots):self.giraffe_spots= spots>>> ozwald = Giraffes(100)>>> gertrude = Giraffes(150)>>> print(ozwald.giraffe_spots)100>>> print(gertrude.giraffe_spots)150初期化函數的例子初期化函數的使用實例第九章python自帶的常用函數PYTHON學習PYTHON學習1. Python自帶函數-1獲得絕對值abs()>>> print(abs(10))10布爾變量bool()>>> print(bool(0))False>>> print(bool(1))True>>> print(bool('a'))Dir函數>>> print(bool(0))False>>> print(bool(1))True>>> print(bool('a'))#用它來計算絕對值#用它來取得邏輯真假,可進行IF判斷還記得條件語法嗎if elif else#它的參數是任意類型,執行結果可以告訴你,可以處理這種類型所有的函數。你需要從一堆結果中找出自己有用 的信息。看看下面的記過,對于整數你可以利用那些函數。>>> print(dir(1))['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']PYTHON學習2. Python自帶函數-2獲得幫助help>>> help(abs)Help on built-in function abs in module builtins:abs(x, /)Return the absolute value of the argument.執行命令函數eval>>> your_calculation = input('Enter a calculation: ')Enter a calculation: 12*52>>> eval(your_calculation)624#用它讓Python告訴你函數的使用方法,不過都是英文哦!執行命令函數eval>>> my_small_program = '''print('ham')print('sandwich')'''>>> exec(my_small_program)hamsandwich區別eval可以有返回值exec無返回值PYTHON學習3. Python自帶函數-3浮點值float()>>> print(abs(10))10整數int()>>> float('123.456789')123.456789>>> your_age = input('Enter your age: ')Enter your age: 20>>> age = float(your_age)>>> if age > 13:print('You are %s years too old' % (age - 13))You are 7.0 years too old#帶很多位小數的值>>> int(123.456)123>>> int('123')123>>> int('123.456')Traceback (most recent call last):File "<pyshell>", line 1, in <module>int('123.456')ValueError: invalid literal for int() with base 10: '123.456'出錯了!字符串’123.456’不可以PYTHON學習4. Python自帶函數-4取得長度len>>> len('this is a test string')21>>> creature_list = ['unicorn', 'cyclops', 'fairy', 'elf', 'dragon','troll']>>> print(len(creature_list))6取得最大數,最小值max min>>> numbers = [5, 4, 10, 30, 22]>>> print(max(numbers))30>>> strings = 's,t,r,i,n,g,S,T,R,I,N,G'>>> print(max(strings))t范圍函數range>>> for x in range(0, 5):print(x)>>> count_by_twos = list(range(0, 30, 2))>>> print(count_by_twos)[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]>>> count_down_by_twos = list(range(40, 10, -2))>>> print(count_down_by_twos)[40, 38, 36, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12]PYTHON學習5. Python自帶函數-5計算和文件訪問>>> test_file = open('c:\\test.txt')>>> text = test_file.read()>>> print(text)文件內容xxxxxxxxx>>> my_list_of_numbers = list(range(0, 500, 50))>>> print(my_list_of_numbers)[0, 50, 100, 150, 200, 250, 300, 350, 400, 450]>>> print(sum(my_list_of_numbers))2250>>> test_file = open('c:\\myfile.txt', 'w')>>> test_file.write('What is green and loud A froghorn!')>>> test_file.close()讀取文件寫入文件第十章python常用的模塊PYTHON學習Python模塊是函數、類和變量的集合。為了使它們更容易使用。Python使用模塊來分組函數和類。例如,海龜模塊,我們在前幾章使用它,用它創建的畫布在屏幕上畫畫。PYTHON學習1.復制模塊copy -1導入復制模塊復制模塊的使用實例>>> class Animal:def __init__(self, species, number_of_legs, color):self.species = speciesself.number_of_legs = number_of_legsself.color = colorimportcopy>>> importcopy#導入復制模塊>>> harry = Animal(‘hippogriff’,6,‘pink’)#創建harry對象>>> harriet = copy.copy(harry)#把harry復制到harriet>>>print(harry.species) #輸出harry的species屬性hippogriff>>> print(harriet.species)#輸出hariet的species屬性hippogriff作用 把一個對象復制給另一個對象就像你在復印機上復印資料一樣寫入文件創建一個動物類PYTHON學習2.復制模塊copy-2Copy和deepcopy>>> harry = Animal('hippogriff', 6, 'pink')>>> carrie = Animal('chimera', 4, 'green polka dots')>>> billy = Animal('bogill', 0, 'paisley')>>> my_animals = [harry, carrie, billy]>>> more_animals = copy.copy(my_animals)>>> print(more_animals[0].species)hippogriff>>> print(more_animals[1].species)Chimera>>> my_animals[0].species = 'ghoul'>>> print(my_animals[0].species)ghoul>>> print(more_animals[0].species)ghoul>>> more_animals = copy.deepcopy(my_animals)>>> my_animals[0].species = 'wyrm'>>> print(my_animals[0].species)Wyrm>>> print(more_animals[0].species)ghoulPYTHON學習3. Python的關鍵字模塊關鍵字keyword>>> import keyword>>> print(keyword.iskeyword('if'))True>>> print(keyword.iskeyword('ozwald'))False>>> print(keyword.kwlist)['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class','continue', 'def', 'del', 'elif', 'else', 'except', 'finally','for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda','nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while','with', 'yield']通過關鍵字模塊輸出python關鍵字,幫助我們認識到python語言中那些單詞是有特殊意義的,我們定義變量和函數時需要避開重名。PYTHON學習4.隨機函數模塊randomrandom返回制定范圍的隨機值>>> import random>>> print(random.randint(1, 100))58>>> print(random.randint(100, 1000))861choice從列表隨機取出一個項目>>> import random>>> desserts = ['ice cream', 'pancakes', 'brownies', 'cookies','candy']>>> print(random.choice(desserts))browniesShuffle把列表洗牌重新排序>>> import random>>> desserts = ['ice cream', 'pancakes', 'brownies', 'cookies','candy']>>> random.shuffle(desserts)>>> print(desserts)['pancakes', 'ice cream', 'candy', 'brownies', 'cookies']PYTHON學習5.系統模塊對控制臺進行操作sysexit關閉控制帶>>> import sys>>> sys.exit()stdin.readline從控制臺讀入輸入信息>>> import sys>>> v = sys.stdin.readline()He who laughs last thinksslowest>>> print(v)He who laughs last thinks sloweststdout.write把內容輸出到控制臺>>> import sys>>> sys.stdout.write("What does a fish say when it swims into a wall Dam.")What does a fish say when it swims into a wall Dam.52>>> import sys>>> print(sys.version)3.1.2 (r312:79149, Mar 21 2013, 00:41:52) [MSC v.1500 32 bit (Intel)]version顯示系統版本PYTHON學習6.時間模塊time-1time取得現在時間>>> import time>>> print(time.time())1300139149.34>>> def lots_of_numbers(max):u t1 = time.time()v for x in range(0, max):print(x)w t2 = time.time()x print('it took %s seconds' % (t2-t1))>>> lots_of_numbers(1000)January 1, 1970, at 00:00:00計算經過的時間time.asctime取得可讀的時間>>> import time>>> print(time.asctime())Mon Mar 11 22:03:41 2013>>> import time>>> t = (2020, 2, 23, 10, 30, 48, 6, 0, 0)>>> print(time.asctime(t))Sun Feb 23 10:30:48 2020time.asctime自己定義一個時間PYTHON學習7.時間模塊time-2time.localtime取得現在時間的列表>>> import time>>> print(time.localtime())time.struct_time(tm_year=2020, tm_mon=2, tm_mday=23, tm_hour=22,tm_min=18, tm_sec=39, tm_wday=0, tm_yday=73, tm_isdst=0)>>> t = time.localtime()>>> year = t[0]>>> month = t[1]>>> print(year)2020>>> print(month)2time.sleep讓計算機休息一會兒>>> for x in range(1, 61):print(x)time.sleep(1)PYTHON學習8.保存信息模塊pickle保存map信息到文件>>> import picklev >>> game_data = {'player-position' : 'N23 E45','pockets' : ['keys', 'pocket knife', 'polished stone'],'backpack' : ['rope', 'hammer', 'apple'],'money' : 158.50}w >>> save_file = open('save.dat', 'wb')x >>> pickle.dump(game_data, save_file)y >>> save_file.close()從文件讀取保存的信息>>> load_file = open('save.dat', 'rb')>>> loaded_game_data = pickle.load(load_file)>>> load_file.close()>>> print(loaded_game_data){'money': 158.5, 'backpack': ['rope', 'hammer', 'apple'],'player-position': 'N23 E45', 'pockets': ['keys', 'pocket knife','polished stone']}第十章高級海龜繪圖PYTHON學習PYTHON學習1.進階海龜繪圖運用學到的知識試試海龜畫出下面的圖第十一章 圖形界面PYTHON學習PYTHON學習1.什么是圖形界面你現在使用的計算機就是圖形界面(例如)PYTHON學習2. Python的圖形界面Python的圖形包Importtkinter要開發圖形界面,首先要導入圖形包Python的圖形接口tkniter.Tk()創建基本的窗口Python的窗口控件tkniter.Button()按鍵tkniter.Canvas()用來在窗口畫圖的畫布等等。。。。。Python的窗口更新顯示xxxx.Pack()當你畫了控件xxxx后需要用執行Pack來讓它顯示PYTHON學習3. Python的圖形界面Python的標準圖形控件控件描述Button按鈕控件;在程序中顯示按鈕。Canvas畫布控件;顯示圖形元素如線條或文本Checkbutton多選框控件;用于在程序中提供多項選擇框Entry輸入控件;用于顯示簡單的文本內容Frame框架控件;在屏幕上顯示一個矩形區域,多用來作為容器Label標簽控件;可以顯示文本和位圖Listbox列表框控件;在Listbox窗口小部件是用來顯示一個字符串列表給用戶Menubutton菜單按鈕控件,由于顯示菜單項。Menu菜單控件;顯示菜單欄,下拉菜單和彈出菜單Message消息控件;用來顯示多行文本,與label比較類似Radiobutton單選按鈕控件;顯示一個單選的按鈕狀態Scale范圍控件;顯示一個數值刻度,為輸出限定范圍的數字區間Scrollbar滾動條控件,當內容超過可視化區域時使用,如列表框。.Text文本控件;用于顯示多行文本Toplevel容器控件;用來提供一個單獨的對話框,和Frame比較類似Spinbox輸入控件;與Entry類似,但是可以指定輸入范圍值PanedWindowPanedWindow是一個窗口布局管理的插件,可以包含一個或者多個子控件。LabelFramelabelframe是一個簡單的容器控件。常用與復雜的窗口布局。tkMessageBox用于顯示你應用程序的消息框。PYTHON學習4.實現你的第一個圖形界面import tkinterdef hello():print('hello there')tk=tkinter.Tk()btn= tkinter.Button(tk,text="click me",command=hello,width=8,height=1)btn.pack()canvas = tkinter.Canvas(tk,width=500,height=500)canvas.pack()canvas.create_line(0, 0, 500, 500)導入tkinter定義一個函數,在控制臺輸出hello there創建窗口在窗口加入按鍵,尺寸為8,1顯示click按下按鍵后執行hello函數顯示按鍵創建畫布尺寸為500,500顯示畫布在畫布尺上畫一條線這是執行結果PYTHON學習5.常用的繪圖方法-1繪制盒子import tkinterimport randomtk=tkinter.Tk()canvas = tkinter.Canvas(tk,width=500,height=500)canvas.pack()def random_rectangle(width,height,fill_color):x1= random.randrange(width)y1= random.randrange(height)x2= x1+random.randrange(width)y2= y1+random.randrange(height)canvas.create_rectangle(x1,y1,x2,y2,fill=fill_color)for x in range(0,100):random_rectangle(400,400,'#eb5699')PYTHON學習5.常用的繪圖方法-2繪制圓弧import tkintertk=tkinter.Tk()canvas = tkinter.Canvas(tk,width=500,height=500)canvas.pack()canvas.create_arc(10,10,200,80,extent=359,style=tkinter.ARC)canvas.create_arc(100,100,200,200,extent=359,style=tkinter.ARC)參數的意義1.圖形左上角坐標2.圖形右下角坐標3.繪制角度4.繪制圓弧常量PYTHON學習6.常用的繪圖方法-3繪制多邊形import tkintertk=tkinter.Tk()canvas = tkinter.Canvas(tk,width=500,height=500)canvas.pack()canvas.create_polygon(1,1,100,10,100,110,fill="",outline="black")canvas.create_polygon(200, 10, 240, 30, 120, 100, 140, 120, fill="",outline="black")參數的意義1.給出所有頂點的坐標PYTHON學習7.常用的繪圖方法-4顯示文字import tkintertk=tkinter.Tk()canvas = tkinter.Canvas(tk,width=500,height=500)canvas.pack()canvas.create_text(150, 150, text='He said, "It\'s my curse,',font=('Times', 15))canvas.create_text(200, 200, text='But it could be worse,',font=('Helvetica', 20))canvas.create_text(220, 250, text='My cousin rides round',font=('Courier', 22))canvas.create_text(220, 300, text='on a goose."', font=('Courier', 30))PYTHON學習8.常用的繪圖方法-5顯示背景圖片import tkintertk=tkinter.Tk()canvas = tkinter.Canvas(tk,width=800,height=500)canvas.pack()my_image=tkinter.PhotoImage(file='5414231.gif')canvas.create_image(0,0,anchor=tkinter.NW,image=my_image)注意Tkinter只能處理gif圖片,如果要處理其他圖片需要用到python圖形庫注意NW告訴tkinter圖片左上角是原點,否則將以圖片中心作為原點PYTHON學習9.常用的繪圖方法-6創作你的蒙太奇import tkinterimport timetk=tkinter.Tk()canvas = tkinter.Canvas(tk,width=800,height=500)canvas.pack()mytriangle=canvas.create_polygon(10, 10, 10, 60, 50, 35)forx in range(0, 60):canvas.move(1, 5, 0)tk.update()time.sleep(0.01)defmovetriangle(event):if event.keysym == 'Up':canvas.move(1, 0, -3)canvas.itemconfig(mytriangle, fill='blue')elif event.keysym == 'Down':canvas.move(1, 0, 3)canvas.itemconfig(mytriangle, fill='red')elif event.keysym == 'Left':canvas.move(1, -3, 0)canvas.itemconfig(mytriangle, fill='green')else:canvas.move(1, 3, 0)canvas.itemconfig(mytriangle, fill='black')canvas.bind_all('<KeyPress-Up>', movetriangle)canvas.bind_all('<KeyPress-Down>', movetriangle)canvas.bind_all('<KeyPress-Left>', movetriangle)canvas.bind_all('<KeyPress-Right>', movetriangle)畫三角蒙太奇動作鍵盤事件動作鍵盤事件綁定Move三個參數1.畫布上圖片代號2.X坐標移動距離3.Y坐標移動距離下一階段PYTHON學習恭喜你學完python基本知識,下面可以完成2個簡單的游戲彈球游戲PYTHON學習火柴人游戲PYTHON學習 展開更多...... 收起↑ 資源預覽 縮略圖、資源來源于二一教育資源庫