溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python交互式圖形編程的實現(xiàn)

發(fā)布時間:2020-08-30 21:22:56 來源:腳本之家 閱讀:311 作者:箬笠蓑衣 欄目:開發(fā)技術(shù)

一、

1、圖形顯示

  • 圖素法
  • 像素法
  • 圖素法---矢量圖:以圖形對象為基本元素組成的圖形,如矩形、 圓形
  • 像素法---標(biāo)量圖:以像素點為基本單位形成圖形

2、圖形用戶界面:Graphical User Interface,GUI

  • Tkinter---Python 標(biāo)準(zhǔn)GUI
  • Graphics---基于Tkinter擴展圖形庫
  • Turtle---python內(nèi)置的圖形庫。

3、安裝graphics庫

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

Python交互式圖形編程的實現(xiàn)

4、graphics庫

(1)創(chuàng)建圖形窗口

圖形窗口

點(像素)的集合

GraphWin對象尺寸默認(rèn)值:高200像素,寬200像素。

參考坐標(biāo)系

  • n Graphics\Tkinter
  • n 點(0,0)表示屏幕左上角
  • n X軸正方向為從左到右
  • n Y軸正方向為從上到下。
  • n 默認(rèn)窗口大小為200*200

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

簡潔形式

(2)點

Python交互式圖形編程的實現(xiàn)

移動點

move(x,y)方法
清除原來點的圖像,并在新位置重新繪制
兩個數(shù)字參數(shù):x,y

Python交互式圖形編程的實現(xiàn)

(2)圓

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

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

Python交互式圖形編程的實現(xiàn)

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

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)

Python交互式圖形編程的實現(xiàn)

(3)face

from graphics import *

win=GraphWin()
face=Circle(Point(100,95),50)
leftEye=Circle(Point(80,80),5)
leftEye.setFill("yellow")
leftEye.setOutline("red")
rightEye=Circle(Point(120,80),5)
rightEye.setFill("yellow")
rightEye.setOutline("red")
mouth=Line(Point(80,110),Point(120,110))

face.draw(win)
mouth.draw(win)
leftEye.draw(win)
rightEye.draw(win)

Python交互式圖形編程的實現(xiàn)

5、交互式圖形接口

圖形用戶界面(圖形用戶接口),
n 采用圖形方式顯示的計算機操作用戶界面
n 用于程序的輸入和輸出
n 事件驅(qū)動

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

(1)捕捉鼠標(biāo)點擊

from graphics import *

def main():
  win=GraphWin("Click me")#標(biāo)題欄名
  for i in range(10):
    p=win.getMouse()
    print("you click at:",p.getX(),p.getY())
if __name__=="__main__":
  main()

Python交互式圖形編程的實現(xiàn)

(2)四邊形

from graphics import *

def main():
  win=GraphWin("draw a polygon",500,500)#標(biāo)題欄名
  win.setCoords(0,0,500,500)#變換坐標(biāo),左下角和右上角
  message=Text(Point(250,50),"click on four points")#下面中心位置
  message.draw(win)
  
  #獲取四個點
  p1=win.getMouse()
  p1.draw(win)
  p2=win.getMouse()
  p2.draw(win)
  p3=win.getMouse()
  p3.draw(win)
  p4=win.getMouse()
  p4.draw(win)

  #順次畫出閉合圖形
  polygon=Polygon(p1,p2,p3,p4)
  polygon.setFill("red")
  polygon.setOutline('black')
  polygon.draw(win)

  message.setText('click anywhere to quit')
  win.getMouse()
  
if __name__=="__main__":
  main()

Python交互式圖形編程的實現(xiàn)

6、溫度轉(zhuǎn)換界面

(1)輸入窗口

from graphics import *
 
win = GraphWin("Celsius Converter", 400, 300)#載入界面,標(biāo)題欄
win.setCoords(0.0, 0.0, 3.0, 4.0)#按比例轉(zhuǎn)換坐標(biāo)

# 繪制接口
Text(Point(1,3), " Celsius Temperature:").draw(win)#輸入文字
Text(Point(1,1), "Fahrenheit Temperature:").draw(win)

input= Entry(Point(2,3),5)#前面是位置,后面是寬度,可以寫數(shù)字
input.setText("0.0")
input.draw(win)

Python交互式圖形編程的實現(xiàn)

Entry輸入可以讓用戶自己輸入內(nèi)容,setText()是填充入內(nèi)容,用戶可以修改。

(2)完整代碼

from graphics import *
 
win = GraphWin("Celsius Converter", 400, 300)#載入界面,標(biāo)題欄
win.setCoords(0.0, 0.0, 3.0, 4.0)#按比例轉(zhuǎn)換坐標(biāo)

# 繪制接口
Text(Point(1,3), " Celsius Temperature:").draw(win)#輸入文字
Text(Point(1,1), "Fahrenheit Temperature:").draw(win)

input= Entry(Point(2,3),5)#前面是位置,后面是寬度,可以寫數(shù)字
input.setText("0.0")
input.draw(win)

output = Text(Point(2,1),"")#確定輸出位置
output.draw(win)

button = Text(Point(1.5,2.0),"Convert It")#按鈕字樣
button.draw(win)
Rectangle(Point(1,1.5), Point(2,2.5)).draw(win)#長方形

# 等待鼠標(biāo)點擊
win.getMouse()
# 轉(zhuǎn)換輸入
celsius = eval(input.getText())#得到你的輸入值,getText()

fahrenheit = 9.0/5.0 * celsius + 32.0
# 顯示輸出,改變按鈕
output.setText(fahrenheit)#輸出溫度值,setText()
button.setText("Quit")
# 等待響應(yīng)鼠標(biāo)點擊,退出程序
win.getMouse()
win.close()

Python交互式圖形編程的實現(xiàn)

體會Text和Entry的區(qū)別,前者只能由程序輸入內(nèi)容,后者可以在圖形界面輸入內(nèi)容;兩者都是用getText()獲取內(nèi)容,用setText()展示內(nèi)容。

三、tkinter庫

7、創(chuàng)建GUI程序的基本步驟為:
n 導(dǎo)入Tk模塊.
n 創(chuàng)建GUI應(yīng)用程序的主窗口.
n 添加控件或GUI應(yīng)用程序.
n 進入主事件循環(huán),等待響應(yīng)用戶觸發(fā)事件

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

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

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

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

創(chuàng)建GUI應(yīng)用程序窗口代碼模板

Python交互式圖形編程的實現(xiàn)

from tkinter import *

tk=Tk()
label=Label(tk,text="welcome to python Tkinter")#標(biāo)簽
button=Button(tk,text="click me")#按鈕
label.pack()
button.pack()
tk.mainloop()

Python交互式圖形編程的實現(xiàn)

(2)響應(yīng)用戶事件示例

from tkinter import *

def processOK():
    print("OK button is clicked")#點擊之后會在idle中顯示

def processCancel():
    print("cancel button is clicked")

def main():
    tk=Tk()
    btnOK=Button(tk,text="OK",fg="red",command=processOK)#文本,字體顏色,和點擊評論,并沒有標(biāo)定具體位置,
    btnCancel=Button(tk,text="cancel ",bg="yellow",command=processCancel)
    btnOK.pack()
    btnCancel.pack()

    tk.mainloop()

if __name__=="__main__":
    main()

Python交互式圖形編程的實現(xiàn)

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

Python交互式圖形編程的實現(xiàn)

from tkinter import *

def main():
    tk=Tk()
    canvas=Canvas(tk,width=300,height=200)#創(chuàng)建畫布,寬和高
    canvas.pack()#顯示畫布
    #創(chuàng)建文字,(150,40)中心點,內(nèi)容,顏色,字體,大小
    canvas.create_text(150,40,text="welcome to Tkinter",fill='blue',font=("Times",16))
    
    myImage=PhotoImage(file="python_logo.gif")
    #創(chuàng)建圖片,只能gif格式,(65,70)左上角坐標(biāo)
    canvas.create_image(65,70,anchor="nw",image=myImage)
    
    canvas.create_rectangle(65,70,240,130)

    tk.mainloop()
if __name__=="__main__":
    main()

Python交互式圖形編程的實現(xiàn)

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

from tkinter import *

tk=Tk()
canvas=Canvas(tk,width=400,height=400)#創(chuàng)建畫布
canvas.pack()

def moverectangle(event):
    if event.keysym=="Up":#獲取你點擊的鍵盤內(nèi)容
        canvas.move(1,0,-5)
        print(event.keysym)

    elif event.keysym=="Down":
        canvas.move(1,0,5)
        print(event.keysym)

    elif event.keysym=="Left":
        canvas.move(1,-5,0)
        print(event.keysym)

    elif event.keysym=="Right":
        canvas.move(1,5,0)
        print(event.keysym)

canvas.create_rectangle(10,10,50,50,fill="red")#畫出方塊

canvas.bind_all("<KeyPress-Up>",moverectangle)#通過鍵盤,觸發(fā)函數(shù)
canvas.bind_all("<KeyPress-Down>",moverectangle)
canvas.bind_all("<KeyPress-Left>",moverectangle)
canvas.bind_all("<KeyPress-Right>",moverectangle)

Python交互式圖形編程的實現(xiàn)

四、圖形庫的應(yīng)用方法

1、Graphwin對象

一個程序可以定義任意數(shù)量的窗體
n GraphWin()
n 默認(rèn)標(biāo)題是“Graphics Window”
n 默認(rèn)大小為200*200

Python交互式圖形編程的實現(xiàn)

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

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

3、圖形顏色

Python中顏色由字符串指定
n 很多顏色具有不同深淺
n 紅色逐漸加深
n ‘red1' ‘red2' ‘red3' ‘red4

color_rgb(red,green,blue)函數(shù)
n 設(shè)定顏色數(shù)值獲得顏色
n 三個參數(shù)為0-255范圍內(nèi)的整數(shù)
n 返回一個字符串
color_rgb(255,0,0) 亮紅色,
color_rgb(130,0,130) 中度洋紅色

from graphics import *
 
def convert(input):
  celsius = eval(input.getText())  # 輸入轉(zhuǎn)換
  fahrenheit = 9.0/5.0 * celsius + 32
  return fahrenheit 

#顏色變化算法
def colorChange(win,input):
  cnum = eval(input.getText())
  weight =cnum / 100.0
  newcolor =color_rgb(int(255*weight),int(66+150*(1-weight)),int(255*(1-weight)))#算法核心
  win.setBackground(newcolor)
  
def main():
  win = GraphWin("Celsius Converter", 400, 300)
  win.setCoords(0.0, 0.0, 3.0, 4.0)
  
  # 繪制輸入接口,三行提示
  Text(Point(1,3),
     " Celsius Temperature:").draw(win)
  Text(Point(2,2.7),
     " (Please input 0.0-100.0 )").draw(win)
  Text(Point(1,1),
     "Fahrenheit Temperature:").draw(win)
  
  input = Entry(Point(2,3), 5)
  input.setText("0.0")
  input.draw(win)
  
  output = Text(Point(2,1),"")
  output.draw(win)
  
  button = Text(Point(1.5,2.0),"Convert It")
  button.draw(win)
  
  rect = Rectangle(Point(1,1.5), Point(2,2.5))
  rect.draw(win)
  # 等待鼠標(biāo)點擊
  win.getMouse()
  print(win.getMouse())
  result = convert(input)  # 轉(zhuǎn)換輸入
  output.setText(result)  # 顯示輸出 
  # 改變顏色
  colorChange(win,input)
  # 改變按鈕字體
  button.setText("Quit")
  # 等待點擊事件,退出程序
  win.getMouse()
  win.close()
 
if __name__ == '__main__':
  main()

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

五、turtle庫

Turtle 庫
n Python內(nèi)置圖形化模塊

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

Python交互式圖形編程的實現(xiàn)

from turtle import *

def main():
    pensize(3)
    penup()
    goto(-200,-50)
    pendown()
    begin_fill()
    color("red")
    circle(40,steps=3)
    end_fill()

    pensize(3)
    penup()
    goto(-100,-50)
    pendown()
    begin_fill()
    color("green")
    circle(40,steps=4)
    end_fill()

    pensize(3)
    penup()
    goto(0,-50)
    pendown()
    begin_fill()
    color("blue")
    circle(40,steps=5)
    end_fill()

    pensize(3)
    penup()
    goto(100,-50)
    pendown()
    begin_fill()
    color("yellow")
    circle(40,steps=6)
    end_fill()

    pensize(3)
    penup()
    goto(200,-50)
    pendown()
    begin_fill()
    color("purple")
    circle(40)
    end_fill()

    color("green")
    penup()
    goto(-100,50)
    pendown()
    write(("cool colorful shapes"),
       font=("Times",18,"bold"))
    hideturtle()
    
if __name__=="__main__":
    main()

Python交互式圖形編程的實現(xiàn)

六、tkinter庫的聊天界面

(1)

from tkinter import *
import time
 
def main():
 
 def sendMsg():#發(fā)送消息
  strMsg = '我:' + time.strftime("%Y-%m-%d %H:%M:%S",
                 time.localtime()) + '\n '
  txtMsgList.insert('0.0', strMsg, 'greencolor')#END,文本結(jié)尾,也即開頭。后面是標(biāo)簽名稱
  txtMsgList.insert('0.0', txtMsg.get('0.0', END))#"0.0",文本開頭
  txtMsg.delete('0.0', END)
   
 def cancelMsg():#取消消息
  txtMsg.delete('0.0', END)
 
 def sendMsgEvent(event): #發(fā)送消息事件
  if event.keysym == "Up":
   sendMsg()
 
 #創(chuàng)建窗口 
 t = Tk()
 t.title('與python聊天中')
    
 #創(chuàng)建frame容器
 frmLT = Frame(width=500, height=320, bg='white')
 frmLC = Frame(width=500, height=150, bg='white')
 frmLB = Frame(width=500, height=30)
 frmRT = Frame(width=200, height=500)
  
 #創(chuàng)建控件
 txtMsgList = Text(frmLT)
 txtMsgList.tag_config('greencolor', foreground='red')#創(chuàng)建tag,
                            #"greencolor"是名稱,后面是顏色
 txtMsg = Text(frmLC);
 txtMsg.bind("<KeyPress-Up>", sendMsgEvent)
 btnSend = Button(frmLB, text='發(fā) 送', width = 8, command=sendMsg)
 btnCancel = Button(frmLB, text='取消', width = 8, command=cancelMsg)
 imgInfo = PhotoImage(file = "python_logo.gif")
 lblImage = Label(frmRT, image = imgInfo)
 lblImage.image = imgInfo
 
 #窗口布局columnspan選項可以指定控件跨越多列顯示,
 #而rowspan選項同樣可以指定控件跨越多行顯示。
 frmLT.grid(row=0, column=0, columnspan=2, padx=1, pady=3)
 frmLC.grid(row=1, column=0, columnspan=2, padx=1, pady=3)
 frmLB.grid(row=2, column=0, columnspan=2)
 frmRT.grid(row=0, column=2, rowspan=3, padx=2, pady=3)
 #固定大小
 frmLT.grid_propagate(0)
 frmLC.grid_propagate(0)
 frmLB.grid_propagate(0)
 frmRT.grid_propagate(0)
  
 btnSend.grid(row=2, column=0)
 btnCancel.grid(row=2, column=1)
 lblImage.grid()
 txtMsgList.grid()
 txtMsg.grid()
 
 #主事件循環(huán)
 t.mainloop()
 
if __name__ == '__main__':
  main()

Python交互式圖形編程的實現(xiàn)

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

tag()設(shè)置標(biāo)簽格式(顏色)

time()輸出時間

insert()一定要注意,是從開頭插入還是末尾插入,否則就出現(xiàn)了上述的情況,新輸入的在上方

更改如下

from tkinter import *
import time
 
def main():
 
 def sendMsg():#發(fā)送消息
  strMsg = '我:' + time.strftime("%Y-%m-%d %H:%M:%S",
                 time.localtime()) + '\n '
  print(strMsg)
  txtMsgList.insert(END, strMsg,"greencolor")#插入年月日
  txtMsgList.insert(END, txtMsg.get('0.0', END))#輸入的內(nèi)容,0.0表示文本開始
  txtMsg.delete('0.0', END)#刪除中間剛輸入的內(nèi)容
   
 def cancelMsg():#取消消息
  txtMsg.delete('0.0', END)
 
 def sendMsgEvent(event): #發(fā)送消息事件:
  if event.keysym == "Up":
   sendMsg()
 
 #創(chuàng)建窗口 
 t = Tk()
 t.title('與python聊天中')
    
 #創(chuàng)建frame容器
 frmLT = Frame(width=500, height=320, bg='white')
 frmLC = Frame(width=500, height=150, bg='white')
 frmLB = Frame(width=500, height=30)
 frmRT = Frame(width=200, height=500)
  
 #創(chuàng)建控件
 txtMsgList = Text(frmLT)
 # txtMsgList.tag_config('greencolor', foreground='#008C00')#創(chuàng)建tag
 txtMsg = Text(frmLC);
 txtMsg.bind("<KeyPress-Up>", sendMsgEvent)

 #發(fā)送取消按鈕和圖片
 btnSend = Button(frmLB, text='發(fā) 送', width = 8, command=sendMsg)
 btnCancel = Button(frmLB, text='取消', width = 8, command=cancelMsg)
 imgInfo = PhotoImage(file = "python_logo.gif")
 lblImage = Label(frmRT, image = imgInfo)
 lblImage.image = imgInfo
 
 #窗口布局columnspan選項可以指定控件跨越多列顯示,
 #而rowspan選項同樣可以指定控件跨越多行顯示。
 frmLT.grid(row=0, column=0,columnspan=2, padx=1, pady=3)
 frmLC.grid(row=1, column=0, columnspan=2,padx=1, pady=3)
 frmLB.grid(row=2, column=0,columnspan=2)
 frmRT.grid(row=0, column=2, columnspan=2,rowspan=3, padx=2, pady=3)
 #固定大小
 frmLT.grid_propagate(0)
 frmLC.grid_propagate(0)
 frmLB.grid_propagate(0)
 frmRT.grid_propagate(0)

  #按鈕和圖片
 btnSend.grid(row=2,column=0)
 btnCancel.grid(row=2,column=1)
 lblImage.grid()
 
 txtMsgList.grid()
 txtMsg.grid()
 
 #主事件循環(huán)
 t.mainloop()
 
if __name__ == '__main__':
  main()

Python交互式圖形編程的實現(xiàn)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI