日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?tkinter庫繪圖實例分享_python

作者:簡時刻 ? 更新時間: 2022-06-11 編程語言

一、小房子繪制

實例代碼:

# coding=utf-8
import tkinter as tk ? ? ?# 導入tkinter模塊
?
root = tk.Tk() ? ? ? ? ? ?# 創(chuàng)建一個頂級窗口
root.title('小房子1') ? ? # 設置標題
canvas = tk.Canvas(root, bg='white', width=700, height=700) ? # 在root窗口上創(chuàng)建畫布canvas,白色背景,寬和高均為700像素
canvas.pack(anchor='center') ? # canvas在root上居中顯示
?
points = [(50, 250), (350, 50), (650, 250)] ? # 三角形頂點坐標位置
canvas.create_polygon(points, fill='gray', outline='black', width=10) ? # 白色填充,紅色線條,線寬為10
canvas.create_rectangle((200, 250, 500, 550),
? ? ? ? ? ? ? ? ? ? ? ? fill='white', outline='black', width=10) ? ? # 繪制矩形,白色填充,綠色線條,線寬為10
canvas.create_oval((250, 300, 450, 500),
? ? ? ? ? ? ? ? ? ?fill='purple', outline='black', width=10) ? ?# 繪制圓形,黃色填充,黃色線條,線寬為10
?
root.mainloop() ? # 進入消息循環(huán)

運行結果:

二、彩色氣泡動畫繪制

實例代碼:

#coding=utf-8
import tkinter as tk
import random as rd
import time
# 全局變量,全部為list對象
# 分別為:x方向速度,y方向速度,半徑,位置,圖形標記
speedXList, speedYList, rList, posList, idList = [], [], [], [], []
# 可選的顏色
colorList = ['pink', 'gold', 'lightblue', 'lightgreen', 'silver']
# 畫布的寬度、高度,以及圖形個數
width, height, num = 400, 400, 5
root = tk.Tk()
# 創(chuàng)建和布局畫布
canvas = tk.Canvas(root, width=width, height=height, background='white')
canvas.pack()
?
for i in range(num):
?? ?# 隨機產生圖形初始位置
? ? x = rd.randint(100, width - 100)
? ? y = rd.randint(100, height - 100)
? ? # 添加到圖形位置列表
? ? posList.append((x, y))
? ? # 隨機產生半徑,并添加到半徑列表
? ? r = rd.randint(20, 50)
? ? rList.append(r)
? ? # 隨機選取一種顏色
? ? color = rd.sample(colorList, 1)
? ? # 創(chuàng)建一個橢圓/圓,用選定的顏色填充
? ? id = canvas.create_oval(x - r, y - r, x + r, y + r,
? ? ? ? ? ? ? ? ? ? ? ? ? ? fill=color, outline=color)
? ? # 保存圖形標識
? ? idList.append(id)
# 設置隨機的移動速度,并保存
? ? speedXList.append(rd.randint(-10, 10))
? ? speedYList.append(rd.randint(-10, 10))
?
while True:
? ? for i in range(num):
? ? ? ? # 圖形當前所在位置
? ? ? ? item = posList[i]
? ? ? ? r = rList[i]
? ? ? ? ?# 如果x位置超過邊界,則改編x速度方向
? ? ? ? if item[0] - r < 0 or item[0] + r > width:
? ? ? ? ? ? speedXList[i] = -speedXList[i]
? ? ? ? # 如果y位置超過邊界,則改編y速度方向
? ? ? ? if item[1] - r < 0 or item[1] + r > height:
? ? ? ? ? ? speedYList[i] = -speedYList[i]
? ? ? ? # 按照當前的速度計算下新的位置
? ? ? ? posList[i] = (item[0] + speedXList[i], item[1] + speedYList[i])
? ? ? ? x, y = posList[i][0], posList[i][1]
? ? ? ? # 移動到新的位置
? ? ? ? canvas.coords(idList[i], (x - r, y - r, x + r, y + r))
? ? ? ? # 刷新畫面
? ? ? ? canvas.update()
? ? # 等待0.1秒,即每秒鐘更新10幀,形成動畫
? ? time.sleep(0.1)

運行結果:

三、畫布創(chuàng)建

實例代碼:

import tkinter as tk ? ? ? ? ? # 導入tkinter庫,并重命名為tk
mywindow = tk.Tk() ? ? ? ? ? ? # 創(chuàng)建一個窗體
mywindow.title("我是一個畫布") ? ? ?# 設置窗體的標題
mycanvas = tk.Canvas(mywindow, width=400, height=300, bg="purple") ?# 創(chuàng)建畫布并布局
?
mycanvas.pack()
mywindow.mainloop() ? ? ?# 顯示畫布

運行結果:

原文鏈接:https://blog.csdn.net/weixin_44940488/article/details/124062048?spm=1001.2014.3001.5502

欄目分類
最近更新