Python——交互式圖形編程

1、python

一、圖形顯示算法

圖素法canvas

像素法ide

圖素法---矢量圖:以圖形對象爲基本元素組成的圖形,如矩形、 圓形函數

像素法---標量圖:以像素點爲基本單位造成圖形 oop

二、圖形用戶界面:Graphical User Interface,GUI佈局

Tkinter---Python 標準GUI字體

Graphics---基於Tkinter擴展圖形庫ui

Turtle---python內置的圖形庫。 spa

三、安裝graphics庫

安裝在D:\Python3\Lib\site-packages,網址http://mcsp.wartburg.edu/zelle/python/graphics.py

2、

四、graphics庫

(1)建立圖形窗口

圖形窗口

點(像素)的集合

GraphWin對象尺寸默認值:高200像素,寬200像素。 

參考座標系
Graphics\Tkinter
點(0,0)表示屏幕左上角
X軸正方向爲從左到右
Y軸正方向爲從上到下。
默認窗口大小爲200*200

簡潔形式

(2)點

 

移動點

move(x,y)方法
清除原來點的圖像,並在新位置從新繪製
兩個數字參數:x,y

(2)圓

 1 from graphics import *
 2 win=GraphWin()
 3 leftEye=Circle(Point(80,80),5)
 4 leftEye.setFill("yellow")
 5 leftEye.setOutline("red")
 6 rightEye=leftEye
 7 rightEye.move(40,0)
 8 
 9 leftEye.draw(win)
10 rightEye.draw(win)

左眼右眼重疊了,說明,移動後原來的圖就不存在了。

from graphics import *
win=GraphWin()
leftEye=Circle(Point(80,80),5)
leftEye.setFill("yellow")
leftEye.setOutline("red")
rightEye=Circle(Point(120,80),5)
rightEye.setFill("yellow")
rightEye.setOutline("red")

leftEye.draw(win)
rightEye.draw(win)

(3)face

 1 from graphics import *
 2 
 3 win=GraphWin()
 4 face=Circle(Point(100,95),50)
 5 leftEye=Circle(Point(80,80),5)
 6 leftEye.setFill("yellow")
 7 leftEye.setOutline("red")
 8 rightEye=Circle(Point(120,80),5)
 9 rightEye.setFill("yellow")
10 rightEye.setOutline("red")
11 mouth=Line(Point(80,110),Point(120,110))
12 
13 face.draw(win)
14 mouth.draw(win)
15 leftEye.draw(win)
16 rightEye.draw(win)

五、交互式圖形接口

圖形用戶界面(圖形用戶接口),
採用圖形方式顯示的計算機操做用戶界面
用於程序的輸入和輸出
事件驅動

Graphics模塊
隱藏了底層事件的處理機制,
提供了得到用戶在窗口中的輸入
捕捉鼠標點擊
處理文本輸入

(1)捕捉鼠標點擊

 1 from graphics import *
 2 
 3 def main():
 4     win=GraphWin("Click me")#標題欄名
 5     for i in range(10):
 6         p=win.getMouse()
 7         print("you click at:",p.getX(),p.getY())
 8 if __name__=="__main__":
 9     main()
10     

 

 

(2)四邊形

 1 from graphics import *
 2 
 3 def main():
 4     win=GraphWin("draw a polygon",500,500)#標題欄名
 5     win.setCoords(0,0,500,500)#變換座標,左下角和右上角
 6     message=Text(Point(250,50),"click on four points")#下面中心位置
 7     message.draw(win)
 8     
 9     #獲取四個點
10     p1=win.getMouse()
11     p1.draw(win)
12     p2=win.getMouse()
13     p2.draw(win)
14     p3=win.getMouse()
15     p3.draw(win)
16     p4=win.getMouse()
17     p4.draw(win)
18 
19     #順次畫出閉合圖形
20     polygon=Polygon(p1,p2,p3,p4)
21     polygon.setFill("red")
22     polygon.setOutline('black')
23     polygon.draw(win)
24 
25     message.setText('click anywhere to quit')
26     win.getMouse()
27     
28 if __name__=="__main__":
29     main()
30     

六、溫度轉換界面

 (1)輸入窗口

 1 from graphics import *
 2  
 3 win = GraphWin("Celsius Converter", 400, 300)#載入界面,標題欄
 4 win.setCoords(0.0, 0.0, 3.0, 4.0)#按比例轉換座標
 5 
 6 # 繪製接口
 7 Text(Point(1,3), " Celsius Temperature:").draw(win)#輸入文字
 8 Text(Point(1,1), "Fahrenheit Temperature:").draw(win)
 9 
10 input= Entry(Point(2,3),5)#前面是位置,後面是寬度,能夠寫數字
11 input.setText("0.0")
12 input.draw(win)

Entry輸入可讓用戶本身輸入內容,setText()是填充入內容,用戶能夠修改。

(2)完整代碼

 1 from graphics import *
 2  
 3 win = GraphWin("Celsius Converter", 400, 300)#載入界面,標題欄
 4 win.setCoords(0.0, 0.0, 3.0, 4.0)#按比例轉換座標
 5 
 6 # 繪製接口
 7 Text(Point(1,3), " Celsius Temperature:").draw(win)#輸入文字
 8 Text(Point(1,1), "Fahrenheit Temperature:").draw(win)
 9 
10 input= Entry(Point(2,3),5)#前面是位置,後面是寬度,能夠寫數字
11 input.setText("0.0")
12 input.draw(win)
13 
14 output = Text(Point(2,1),"")#肯定輸出位置
15 output.draw(win)
16 
17 button = Text(Point(1.5,2.0),"Convert It")#按鈕字樣
18 button.draw(win)
19 Rectangle(Point(1,1.5), Point(2,2.5)).draw(win)#長方形
20 
21 # 等待鼠標點擊
22 win.getMouse()
23 # 轉換輸入
24 celsius = eval(input.getText())#獲得你的輸入值,getText()
25 
26 fahrenheit = 9.0/5.0 * celsius + 32.0
27 # 顯示輸出,改變按鈕
28 output.setText(fahrenheit)#輸出溫度值,setText()
29 button.setText("Quit")
30 # 等待響應鼠標點擊,退出程序
31 win.getMouse()
32 win.close()

體會Text和Entry的區別,前者只能由程序輸入內容,後者能夠在圖形界面輸入內容;二者都是用getText()獲取內容,用setText()展現內容。

 3、tkinter庫

七、建立GUI程序的基本步驟爲:
導入Tk模塊.
建立GUI應用程序的主窗口.
添加控件或GUI應用程序.
進入主事件循環,等待響應用戶觸發事件

15種常見的 Tk 控件
Button, Canvas, Checkbutton, Entry, Frame, Label,
Listbox, Menubutton, Menu, Message, Radiobutton,
Scale Scrollbar, Text, Toplevel, Spinbox
PanedWindow, LabelFrame, tkMessageBox

 

共同屬性
Dimensions :尺寸
Colors:顏色
Fonts:字體
Anchors:錨
Relief styles:浮雕式
Bitmaps:顯示位圖
Cursors:光標的外形

 

(1)界面佈局
Tkinter三種幾何管理方法
pack()
grid()
place()

建立GUI應用程序窗口代碼模板

1 from tkinter import *
2 
3 tk=Tk()
4 label=Label(tk,text="welcome to python Tkinter")#標籤
5 button=Button(tk,text="click me")#按鈕
6 label.pack()
7 button.pack()
8 tk.mainloop()

 (2)響應用戶事件示例

 1 from tkinter import *
 2 
 3 def processOK():
 4         print("OK button is clicked")#點擊以後會在idle中顯示
 5 
 6 def processCancel():
 7         print("cancel button is clicked")
 8 
 9 def main():
10         tk=Tk()
11         btnOK=Button(tk,text="OK",fg="red",command=processOK)#文本,字體顏色,和點擊評論,並無標定具體位置,
12         btnCancel=Button(tk,text="cancel ",bg="yellow",command=processCancel)
13         btnOK.pack()
14         btnCancel.pack()
15 
16         tk.mainloop()
17 
18 if __name__=="__main__":
19         main()

(3)顯示文字、圖片、繪製圖形

 1 from tkinter import *
 2 
 3 def main():
 4         tk=Tk()
 5         canvas=Canvas(tk,width=300,height=200)#建立畫布,寬和高
 6         canvas.pack()#顯示畫布
 7         #建立文字,(150,40)中心點,內容,顏色,字體,大小
 8         canvas.create_text(150,40,text="welcome to Tkinter",fill='blue',font=("Times",16))
 9         
10         myImage=PhotoImage(file="python_logo.gif")
11         #建立圖片,只能gif格式,(65,70)左上角座標
12         canvas.create_image(65,70,anchor="nw",image=myImage)
13         
14         canvas.create_rectangle(65,70,240,130)
15 
16         tk.mainloop()
17 if __name__=="__main__":
18         main()

(4)控制圖形移動的示例

 1 from tkinter import *
 2 
 3 tk=Tk()
 4 canvas=Canvas(tk,width=400,height=400)#建立畫布
 5 canvas.pack()
 6 
 7 def moverectangle(event):
 8         if event.keysym=="Up":#獲取你點擊的鍵盤內容
 9                 canvas.move(1,0,-5)
10                 print(event.keysym)
11 
12         elif event.keysym=="Down":
13                 canvas.move(1,0,5)
14                 print(event.keysym)
15 
16         elif event.keysym=="Left":
17                 canvas.move(1,-5,0)
18                 print(event.keysym)
19 
20         elif event.keysym=="Right":
21                 canvas.move(1,5,0)
22                 print(event.keysym)
23 
24 canvas.create_rectangle(10,10,50,50,fill="red")#畫出方塊
25 
26 canvas.bind_all("<KeyPress-Up>",moverectangle)#經過鍵盤,觸發函數
27 canvas.bind_all("<KeyPress-Down>",moverectangle)
28 canvas.bind_all("<KeyPress-Left>",moverectangle)
29 canvas.bind_all("<KeyPress-Right>",moverectangle)
30         

4、圖形庫的應用方法

一、Graphwin對象

一個程序能夠定義任意數量的窗體
GraphWin()
默認標題是「Graphics Window」
默認大小爲200*200

 

二、圖形對象
點、 線段、 圓、 橢圓、 矩形、 多邊形以及文本
默認初始化
黑色邊框
沒有被填充

 

三、圖形顏色

Python中顏色由字符串指定
不少顏色具備不一樣深淺
紅色逐漸加深
‘red1’ ‘red2’ ‘red3’ ‘red4

color_rgb(red,green,blue)函數
設定顏色數值得到顏色
三個參數爲0-255範圍內的整數
返回一個字符串
color_rgb(255,0,0) 亮紅色,
color_rgb(130,0,130) 中度洋紅色

 1 from graphics import *
 2  
 3 def convert(input):
 4     celsius = eval(input.getText())    # 輸入轉換
 5     fahrenheit = 9.0/5.0 * celsius + 32
 6     return fahrenheit 
 7 
 8 #顏色變化算法
 9 def colorChange(win,input):
10     cnum = eval(input.getText())
11     weight =cnum / 100.0
12     newcolor =color_rgb(int(255*weight),int(66+150*(1-weight)),int(255*(1-weight)))#算法核心
13     win.setBackground(newcolor)
14     
15 def main():
16     win = GraphWin("Celsius Converter", 400, 300)
17     win.setCoords(0.0, 0.0, 3.0, 4.0)
18     
19     # 繪製輸入接口,三行提示
20     Text(Point(1,3),
21          " Celsius Temperature:").draw(win)
22     Text(Point(2,2.7),
23          " (Please input 0.0-100.0 )").draw(win)
24     Text(Point(1,1),
25          "Fahrenheit Temperature:").draw(win)
26     
27     input = Entry(Point(2,3), 5)
28     input.setText("0.0")
29     input.draw(win)
30     
31     output = Text(Point(2,1),"")
32     output.draw(win)
33     
34     button = Text(Point(1.5,2.0),"Convert It")
35     button.draw(win)
36     
37     rect = Rectangle(Point(1,1.5), Point(2,2.5))
38     rect.draw(win)
39     # 等待鼠標點擊
40     win.getMouse()
41     print(win.getMouse())
42     result = convert(input)    # 轉換輸入
43     output.setText(result)    # 顯示輸出 
44     # 改變顏色
45     colorChange(win,input)
46     # 改變按鈕字體
47     button.setText("Quit")
48     # 等待點擊事件,退出程序
49     win.getMouse()
50     win.close()
51  
52 if __name__ == '__main__':
53     main()

5、turtle庫

Turtle 庫
Python內置圖形化模塊

 

 1 from turtle import *
 2 
 3 def main():
 4         pensize(3)
 5         penup()
 6         goto(-200,-50)
 7         pendown()
 8         begin_fill()
 9         color("red")
10         circle(40,steps=3)
11         end_fill()
12 
13         pensize(3)
14         penup()
15         goto(-100,-50)
16         pendown()
17         begin_fill()
18         color("green")
19         circle(40,steps=4)
20         end_fill()
21 
22         pensize(3)
23         penup()
24         goto(0,-50)
25         pendown()
26         begin_fill()
27         color("blue")
28         circle(40,steps=5)
29         end_fill()
30 
31         pensize(3)
32         penup()
33         goto(100,-50)
34         pendown()
35         begin_fill()
36         color("yellow")
37         circle(40,steps=6)
38         end_fill()
39 
40         pensize(3)
41         penup()
42         goto(200,-50)
43         pendown()
44         begin_fill()
45         color("purple")
46         circle(40)
47         end_fill()
48 
49         color("green")
50         penup()
51         goto(-100,50)
52         pendown()
53         write(("cool colorful shapes"),
54               font=("Times",18,"bold"))
55         hideturtle()
56         
57 if __name__=="__main__":
58         main()
59                    

 

 6、tkinter庫的聊天界面

(1)

 1 from tkinter import *
 2 import time
 3  
 4 def main():
 5  
 6   def sendMsg():#發送消息
 7     strMsg = '我:' + time.strftime("%Y-%m-%d %H:%M:%S",
 8                                   time.localtime()) + '\n '
 9     txtMsgList.insert('0.0', strMsg, 'greencolor')#END,文本結尾,也即開頭。後面是標籤名稱
10     txtMsgList.insert('0.0', txtMsg.get('0.0', END))#"0.0",文本開頭
11     txtMsg.delete('0.0', END)
12      
13   def cancelMsg():#取消消息
14     txtMsg.delete('0.0', END)
15  
16   def sendMsgEvent(event): #發送消息事件
17     if event.keysym == "Up":
18       sendMsg()
19  
20   #建立窗口 
21   t = Tk()
22   t.title('與python聊天中')
23        
24   #建立frame容器
25   frmLT = Frame(width=500, height=320, bg='white')
26   frmLC = Frame(width=500, height=150, bg='white')
27   frmLB = Frame(width=500, height=30)
28   frmRT = Frame(width=200, height=500)
29    
30   #建立控件
31   txtMsgList = Text(frmLT)
32   txtMsgList.tag_config('greencolor', foreground='red')#建立tag,
33                                                         #"greencolor"是名稱,後面是顏色
34   txtMsg = Text(frmLC);
35   txtMsg.bind("<KeyPress-Up>", sendMsgEvent)
36   btnSend = Button(frmLB, text='發 送', width = 8, command=sendMsg)
37   btnCancel = Button(frmLB, text='取消', width = 8, command=cancelMsg)
38   imgInfo = PhotoImage(file = "python_logo.gif")
39   lblImage = Label(frmRT, image = imgInfo)
40   lblImage.image = imgInfo
41  
42   #窗口布局columnspan選項能夠指定控件跨越多列顯示,
43   #而rowspan選項一樣能夠指定控件跨越多行顯示。
44   frmLT.grid(row=0, column=0, columnspan=2, padx=1, pady=3)
45   frmLC.grid(row=1, column=0, columnspan=2, padx=1, pady=3)
46   frmLB.grid(row=2, column=0, columnspan=2)
47   frmRT.grid(row=0, column=2, rowspan=3, padx=2, pady=3)
48   #固定大小
49   frmLT.grid_propagate(0)
50   frmLC.grid_propagate(0)
51   frmLB.grid_propagate(0)
52   frmRT.grid_propagate(0)
53    
54   btnSend.grid(row=2, column=0)
55   btnCancel.grid(row=2, column=1)
56   lblImage.grid()
57   txtMsgList.grid()
58   txtMsg.grid()
59  
60   #主事件循環
61   t.mainloop()
62  
63 if __name__ == '__main__':
64     main()

利用grid(),對界面進行佈局

tag()設置標籤格式(顏色)

time()輸出時間

insert()必定要注意,是從開頭插入仍是末尾插入,不然就出現了上述的狀況,新輸入的在上方

更改以下

 1 from tkinter import *
 2 import time
 3  
 4 def main():
 5  
 6   def sendMsg():#發送消息
 7     strMsg = '我:' + time.strftime("%Y-%m-%d %H:%M:%S",
 8                                   time.localtime()) + '\n '
 9     print(strMsg)
10     txtMsgList.insert(END, strMsg,"greencolor")#插入年月日
11     txtMsgList.insert(END, txtMsg.get('0.0', END))#輸入的內容,0.0表示文本開始
12     txtMsg.delete('0.0', END)#刪除中間剛輸入的內容
13      
14   def cancelMsg():#取消消息
15     txtMsg.delete('0.0', END)
16  
17   def sendMsgEvent(event): #發送消息事件:
18     if event.keysym == "Up":
19       sendMsg()
20  
21   #建立窗口 
22   t = Tk()
23   t.title('與python聊天中')
24        
25   #建立frame容器
26   frmLT = Frame(width=500, height=320, bg='white')
27   frmLC = Frame(width=500, height=150, bg='white')
28   frmLB = Frame(width=500, height=30)
29   frmRT = Frame(width=200, height=500)
30    
31   #建立控件
32   txtMsgList = Text(frmLT)
33  # txtMsgList.tag_config('greencolor', foreground='#008C00')#建立tag
34   txtMsg = Text(frmLC);
35   txtMsg.bind("<KeyPress-Up>", sendMsgEvent)
36 
37   #發送取消按鈕和圖片
38   btnSend = Button(frmLB, text='發 送', width = 8, command=sendMsg)
39   btnCancel = Button(frmLB, text='取消', width = 8, command=cancelMsg)
40   imgInfo = PhotoImage(file = "python_logo.gif")
41   lblImage = Label(frmRT, image = imgInfo)
42   lblImage.image = imgInfo
43  
44   #窗口布局columnspan選項能夠指定控件跨越多列顯示,
45   #而rowspan選項一樣能夠指定控件跨越多行顯示。
46   frmLT.grid(row=0, column=0,columnspan=2, padx=1, pady=3)
47   frmLC.grid(row=1, column=0, columnspan=2,padx=1, pady=3)
48   frmLB.grid(row=2, column=0,columnspan=2)
49   frmRT.grid(row=0, column=2, columnspan=2,rowspan=3, padx=2, pady=3)
50   #固定大小
51   frmLT.grid_propagate(0)
52   frmLC.grid_propagate(0)
53   frmLB.grid_propagate(0)
54   frmRT.grid_propagate(0)
55 
56    #按鈕和圖片
57   btnSend.grid(row=2,column=0)
58   btnCancel.grid(row=2,column=1)
59   lblImage.grid()
60   
61   txtMsgList.grid()
62   txtMsg.grid()
63  
64   #主事件循環
65   t.mainloop()
66  
67 if __name__ == '__main__':
68     main()

相關文章
相關標籤/搜索