Python tkinter库Canvas操作(附涂鸦、颜色表、围棋盘三个实例)

简介: Python tkinter库Canvas操作(附涂鸦、颜色表、围棋盘三个实例)

tkinter库Canvas操作三个实例



实例一:涂鸦

import tkinter as tk
import pyautogui as ag
from time import sleep
def paint(event):
        x1, y1 = (event.x - 1), (event.y - 1)
        x2, y2 = (event.x + 1), (event.y + 1)
        tCanvas.create_oval(x1, y1, x2, y2, fill = "black")
def moveRect(w,h):
        ag.moveRel(w,0, duration=w/1000)  # moveRel移动  # dragRel拖曳
        ag.moveRel(0,h, duration=h/1000)
        ag.moveRel(-w,0, duration=w/1000)
        ag.moveRel(0,-h, duration=h/1000)
        sleep(0.5)
win = tk.Tk()
W,H = 640,480
X,Y = win.maxsize() #获取屏幕分辨率 或者用: X,Y = ag.size()
winPos = f'{W}x{H}+{(X-W)//2}+{(Y-H)//2}'
win.geometry(winPos)
win.resizable(False, False)
win.title('桌面分辨率:'+str(X)+"x"+str(Y))
win.update()
tCanvas = tk.Canvas(win, width = win.winfo_width(), height = 400, bg = 'white')
tCanvas.pack(side = "top")
tCanvas.bind("<B1-Motion>", paint)
tCanvas.update()
tk.Label(win, text = "画布作图").pack(side = "bottom")
x0,y0 = 150,60
w,h = 350,160
x , y = win.winfo_rootx()+x0, win.winfo_rooty()+y0
ag.moveTo(x, y, duration=0.5)
moveRect(w,h)
#画直线
tCanvas.create_line(x0, y0, x0+w, y0)
tCanvas.create_line(x0+w, y0, x0+w, y0+h)
#可以把左上和右下两个坐标点一起赋值给变量
coord = x0+w, y0+h, x0, y0+h
tCanvas.create_line(coord)
coord = x0, y0+h, x0, y0
tCanvas.create_line(coord, fill = 'blue')
tCanvas.update()
moveRect(w-h/3,h)
#画矩形
coord = x0+1,y0+1,x0+w-1-h/3,y0+h-1
tCanvas.create_rectangle(coord,fill='limegreen')
tCanvas.update()
moveRect(h,h)
#画圆或椭圆
coord = x0,y0,x0+h,y0+h
tCanvas.create_oval(coord,fill='deepskyblue')
tCanvas.update()
x0=x0+h/2
ag.moveRel(h/2,0)
moveRect(w-h/2,h)
coord = x0,y0,x0+w-h/2,y0+h
tCanvas.create_oval(coord,fill='deeppink')
tCanvas.update()
#画扇形、弓形或一段弧
#type = PIESLICE 扇形、CHORD 弓形、ARC 弧形
sleep(1)
coord = 100, 100, 300, 300
tCanvas.create_arc(coord,start=0,extent=180,fill='gold')
tCanvas.update()
sleep(1)
coord = 240, 60, 490, 310
#颜色也可用6位16进制数的GRB值表示
tCanvas.create_arc(coord,style=tk.CHORD,start=10,fill='#7CFC00')
tCanvas.update()
sleep(1)
coord = 180, 10, 470, 300
tCanvas.create_arc(coord,style=tk.ARC,width=3,dash=6,extent=-180)
#参数有很多,可以上网搜相关参数表
win.mainloop()


运行效果图:

202103192117485.png


注:程序运行时,按下鼠标左键就可以在画布上作图,上图 python 字样就是本人所画 ^_^



还有其它作图函数:


# 多边形、三角形

tCanvas.create_polygon((10,100,10,180,100,180),fill='blue')

# 文字

tCanvas.create_text((150,50),text=u'输出文字',anchor=E)

# 位图

bmap={1:'error',2:'info',3:'question',4:'hourglass'}
for i in bmap:
tCanvas.create_bitmap((20*i,20),bitmap=bmap[i])


# 调入图片

img=PhotoImage(file='D:/pictures/exam.gif')
tCanvas.create_image((200,200),image=img)
tCanvas.pack()


实例二:颜色表

import tkinter as tk
win = tk.Tk()
X,Y = win.maxsize() #获取屏幕分辨率
W,H = 1200,800
winPos = f'{W}x{H}+{(X-W)//2}+{(Y-H)//2}'
win.geometry(winPos)
win.resizable(False, False)
winTitle = f'桌面分辨率:{X}x{Y}{" "*6}窗口大小:{W}x{H}'
win.title(winTitle)
win.update()
colorTuple=(
('black',                '#000000'),
('navy',                 '#000080'),
('darkblue',             '#00008B'),
('mediumblue',           '#0000CD'),
('blue',                 '#0000FF'),
('darkgreen',            '#006400'),
('green',                '#008000'),
('teal',                 '#008080'),
('darkcyan',             '#008B8B'),
('deepskyblue',          '#00BFFF'),
('darkturquoise',        '#00CED1'),
('mediumspringgreen',    '#00FA9A'),
('lime',                 '#00FF00'),
('springgreen',          '#00FF7F'),
('aqua',                 '#00FFFF'),
('cyan',                 '#00FFFF'),
('midnightblue',         '#191970'),
('dodgerblue',           '#1E90FF'),
('lightseagreen',        '#20B2AA'),
('forestgreen',          '#228B22'),
('seagreen',             '#2E8B57'),
('darkslategray',        '#2F4F4F'),
('limegreen',            '#32CD32'),
('mediumseagreen',       '#3CB371'),
('turquoise',            '#40E0D0'),
('royalblue',            '#4169E1'),
('steelblue',            '#4682B4'),
('darkslateblue',        '#483D8B'),
('mediumturquoise',      '#48D1CC'),
('indigo',               '#4B0082'),
('darkolivegreen',       '#556B2F'),
('cadetblue',            '#5F9EA0'),
('cornflowerblue',       '#6495ED'),
('mediumaquamarine',     '#66CDAA'),
('dimgray',              '#696969'),
('slateblue',            '#6A5ACD'),
('olivedrab',            '#6B8E23'),
('slategray',            '#708090'),
('lightslategray',       '#778899'),
('mediumslateblue',      '#7B68EE'),
('lawngreen',            '#7CFC00'),
('chartreuse',           '#7FFF00'),
('aquamarine',           '#7FFFD4'),
('maroon',               '#800000'),
('purple',               '#800080'),
('olive',                '#808000'),
('gray',                 '#808080'),
('skyblue',              '#87CEEB'),
('lightskyblue',         '#87CEFA'),
('blueviolet',           '#8A2BE2'),
('darkred',              '#8B0000'),
('darkmagenta',          '#8B008B'),
('saddlebrown',          '#8B4513'),
('darkseagreen',         '#8FBC8F'),
('lightgreen',           '#90EE90'),
('mediumpurple',         '#9370DB'),
('darkviolet',           '#9400D3'),
('palegreen',            '#98FB98'),
('darkorchid',           '#9932CC'),
('yellowgreen',          '#9ACD32'),
('sienna',               '#A0522D'),
('brown',                '#A52A2A'),
('darkgray',             '#A9A9A9'),
('lightblue',            '#ADD8E6'),
('greenyellow',          '#ADFF2F'),
('paleturquoise',        '#AFEEEE'),
('lightsteelblue',       '#B0C4DE'),
('powderblue',           '#B0E0E6'),
('firebrick',            '#B22222'),
('darkgoldenrod',        '#B8860B'),
('mediumorchid',         '#BA55D3'),
('rosybrown',            '#BC8F8F'),
('darkkhaki',            '#BDB76B'),
('silver',               '#C0C0C0'),
('mediumvioletred',      '#C71585'),
('indianred',            '#CD5C5C'),
('peru',                 '#CD853F'),
('chocolate',            '#D2691E'),
('tan',                  '#D2B48C'),
('lightgray',            '#D3D3D3'),
('thistle',              '#D8BFD8'),
('orchid',               '#DA70D6'),
('goldenrod',            '#DAA520'),
('palevioletred',        '#DB7093'),
('crimson',              '#DC143C'),
('gainsboro',            '#DCDCDC'),
('plum',                 '#DDA0DD'),
('burlywood',            '#DEB887'),
('lightcyan',            '#E0FFFF'),
('lavender',             '#E6E6FA'),
('darksalmon',           '#E9967A'),
('violet',               '#EE82EE'),
('palegoldenrod',        '#EEE8AA'),
('lightcoral',           '#F08080'),
('khaki',                '#F0E68C'),
('aliceblue',            '#F0F8FF'),
('honeydew',             '#F0FFF0'),
('azure',                '#F0FFFF'),
('wheat',                '#F5DEB3'),
('beige',                '#F5F5DC'),
('whitesmoke',           '#F5F5F5'),
('mintcream',            '#F5FFFA'),
('ghostwhite',           '#F8F8FF'),
('salmon',               '#FA8072'),
('sandybrown',           '#FAA460'),
('antiquewhite',         '#FAEBD7'),
('linen',                '#FAF0E6'),
('lightgoldenrodyellow', '#FAFAD2'),
('oldlace',              '#FDF5E6'),
('red',                  '#FF0000'),
('fuchsia',              '#FF00FF'),
('magenta',              '#FF00FF'),
('deeppink',             '#FF1493'),
('orangered',            '#FF4500'),
('tomato',               '#FF6347'),
('hotpink',              '#FF69B4'),
('coral',                '#FF7F50'),
('darkorange',           '#FF8C00'),
('lightsalmon',          '#FFA07A'),
('orange',               '#FFA500'),
('lightpink',            '#FFB6C1'),
('pink',                 '#FFC0CB'),
('gold',                 '#FFD700'),
('peachpuff',            '#FFDAB9'),
('navajowhite',          '#FFDEAD'),
('moccasin',             '#FFE4B5'),
('bisque',               '#FFE4C4'),
('mistyrose',            '#FFE4E1'),
('blanchedalmond',       '#FFEBCD'),
('papayawhip',           '#FFEFD5'),
('lavenderblush',        '#FFF0F5'),
('seashell',             '#FFF5EE'),
('cornsilk',             '#FFF8DC'),
('lemonchiffon',         '#FFFACD'),
('floralwhite',          '#FFFAF0'),
('snow',                 '#FFFAFA'),
('yellow',               '#FFFF00'),
('lightyellow',          '#FFFFE0'),
('ivory',                '#FFFFF0'),
('white',                '#FFFFFF'))
tv = tk.Canvas(win, width = win.winfo_width(), height = win.winfo_height())
tv.pack(side = "top")
i = 0
rows = 35
w, h = 40, 10
w1, h1, h2 = 100, 28, 22
for ct in colorTuple:
    j = (i//rows) * 300
    k = i * h2 - (i//rows) * h2 * rows
    x,y = j + w, k + h
    coord = x, y, j + w1, k + h1
    tv.create_rectangle(coord,fill=ct[1])
    tv.create_text((x+70,y+9),text=ct[1],anchor=tk.W,font=("宋体",9))
    tv.create_text((x+120,y+9),text=ct[0],anchor=tk.W,font=("宋体",9))
    i+=1
tv.update()
for i in colorTuple:
    print(i[0],'\t' if len(i[0])>14 else '\t\t' if len(i[0])>6 else '\t\t\t',i[1])




运行效果图:

20210320211452861.png


这些颜色已经足够多了,但据说装了seaborn扩展的话xkcd_rgb包含的颜色数(有英文名称的)会有更多......




实例三:围棋盘

import tkinter as tk
win = tk.Tk()
X,Y = win.maxsize()
W,H = 800,800
winPos = f'{W}x{H}+{(X-W)//2}+{(Y-H)//2}'
winTitle = f'桌面分辨率:{X}x{Y}{" "*6}窗口大小:{W}x{H}'
win.geometry(winPos)
win.resizable(False, False)
win.title(winTitle)
win.update()
tv = tk.Canvas(win, width = win.winfo_width(), height = win.winfo_height())
tv.pack(side = "top")
for i in range(18):
    coord = 40, 40, 760, i*40 + 80
    tv.create_rectangle(coord)
    coord = 40, 40, i*40 + 80, 760
    tv.create_rectangle(coord)
coord = 40, 40, 760, 760
tv.create_rectangle(coord,width=2)
x = (160,160,160,400,400,400,640,640,640)
y = (160,400,640,160,400,640,160,400,640)
for i in range(9):
    tv.create_oval(x[i]-2,y[i]-2,x[i]+2,y[i]+2,fill='black')
tv.update()

运行效果图:

20210320215714268.png



附录


例二输出的颜色列表



black              #000000

navy              #000080

darkblue          #00008B

mediumblue          #0000CD

blue              #0000FF

darkgreen          #006400

green              #008000

teal              #008080

darkcyan          #008B8B

deepskyblue          #00BFFF

darkturquoise          #00CED1

mediumspringgreen      #00FA9A

lime              #00FF00

springgreen          #00FF7F

aqua              #00FFFF

cyan              #00FFFF

midnightblue          #191970

dodgerblue          #1E90FF

lightseagreen          #20B2AA

forestgreen          #228B22

seagreen          #2E8B57

darkslategray          #2F4F4F

limegreen          #32CD32

mediumseagreen          #3CB371

turquoise          #40E0D0

royalblue          #4169E1

steelblue          #4682B4

darkslateblue          #483D8B

mediumturquoise      #48D1CC

indigo              #4B0082

darkolivegreen          #556B2F

cadetblue          #5F9EA0

cornflowerblue          #6495ED

mediumaquamarine      #66CDAA

dimgray          #696969

slateblue          #6A5ACD

olivedrab          #6B8E23

slategray          #708090

lightslategray          #778899

mediumslateblue      #7B68EE

lawngreen          #7CFC00

chartreuse          #7FFF00

aquamarine          #7FFFD4

maroon              #800000

purple              #800080

olive              #808000

gray              #808080

skyblue          #87CEEB

lightskyblue          #87CEFA

blueviolet          #8A2BE2

darkred          #8B0000

darkmagenta          #8B008B

saddlebrown          #8B4513

darkseagreen          #8FBC8F

lightgreen          #90EE90

mediumpurple          #9370DB

darkviolet          #9400D3

palegreen          #98FB98

darkorchid          #9932CC

yellowgreen          #9ACD32

sienna              #A0522D

brown              #A52A2A

darkgray          #A9A9A9

lightblue          #ADD8E6

greenyellow          #ADFF2F

paleturquoise          #AFEEEE

lightsteelblue          #B0C4DE

powderblue          #B0E0E6

firebrick          #B22222

darkgoldenrod          #B8860B

mediumorchid          #BA55D3

rosybrown          #BC8F8F

darkkhaki          #BDB76B

silver              #C0C0C0

mediumvioletred      #C71585

indianred          #CD5C5C

peru              #CD853F

chocolate          #D2691E

tan              #D2B48C

lightgray          #D3D3D3

thistle          #D8BFD8

orchid              #DA70D6

goldenrod          #DAA520

palevioletred          #DB7093

crimson          #DC143C

gainsboro          #DCDCDC

plum              #DDA0DD

burlywood          #DEB887

lightcyan          #E0FFFF

lavender          #E6E6FA

darksalmon          #E9967A

violet              #EE82EE

palegoldenrod          #EEE8AA

lightcoral          #F08080

khaki              #F0E68C

aliceblue          #F0F8FF

honeydew          #F0FFF0

azure              #F0FFFF

wheat              #F5DEB3

beige              #F5F5DC

whitesmoke          #F5F5F5

mintcream          #F5FFFA

ghostwhite          #F8F8FF

salmon              #FA8072

sandybrown          #FAA460

antiquewhite          #FAEBD7

linen              #FAF0E6

lightgoldenrodyellow      #FAFAD2

oldlace          #FDF5E6

red              #FF0000

fuchsia          #FF00FF

magenta          #FF00FF

deeppink          #FF1493

orangered          #FF4500

tomato              #FF6347

hotpink          #FF69B4

coral              #FF7F50

darkorange          #FF8C00

lightsalmon          #FFA07A

orange              #FFA500

lightpink          #FFB6C1

pink              #FFC0CB

gold              #FFD700

peachpuff          #FFDAB9

navajowhite          #FFDEAD

moccasin          #FFE4B5

bisque              #FFE4C4

mistyrose          #FFE4E1

blanchedalmond          #FFEBCD

papayawhip          #FFEFD5

lavenderblush          #FFF0F5

seashell          #FFF5EE

cornsilk          #FFF8DC

lemonchiffon          #FFFACD

floralwhite          #FFFAF0

snow              #FFFAFA

yellow              #FFFF00

lightyellow          #FFFFE0

ivory              #FFFFF0

white              #FFFFFF



目录
相关文章
|
9天前
|
XML JSON 数据库
Python的标准库
Python的标准库
121 77
|
1天前
|
数据挖掘 vr&ar C++
让UE自动运行Python脚本:实现与实例解析
本文介绍如何配置Unreal Engine(UE)以自动运行Python脚本,提高开发效率。通过安装Python、配置UE环境及使用第三方插件,实现Python与UE的集成。结合蓝图和C++示例,展示自动化任务处理、关卡生成及数据分析等应用场景。
16 5
|
23天前
|
机器学习/深度学习 算法 数据挖掘
数据分析的 10 个最佳 Python 库
数据分析的 10 个最佳 Python 库
70 4
数据分析的 10 个最佳 Python 库
|
10天前
|
XML JSON 数据库
Python的标准库
Python的标准库
38 11
|
23天前
|
人工智能 API 开发工具
aisuite:吴恩达发布开源Python库,一个接口调用多个大模型
吴恩达发布的开源Python库aisuite,提供了一个统一的接口来调用多个大型语言模型(LLM)服务。支持包括OpenAI、Anthropic、Azure等在内的11个模型平台,简化了多模型管理和测试的工作,促进了人工智能技术的应用和发展。
90 1
aisuite:吴恩达发布开源Python库,一个接口调用多个大模型
|
10天前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
49 8
|
17天前
|
安全 API 文件存储
Yagmail邮件发送库:如何用Python实现自动化邮件营销?
本文详细介绍了如何使用Yagmail库实现自动化邮件营销。Yagmail是一个简洁强大的Python库,能简化邮件发送流程,支持文本、HTML邮件及附件发送,适用于数字营销场景。文章涵盖了Yagmail的基本使用、高级功能、案例分析及最佳实践,帮助读者轻松上手。
29 4
|
2月前
|
Python
pip批量安装Python库 requirement.txt 离线环境无互联网环境下pip安装Python库
pip批量安装Python库 requirement.txt 离线环境无互联网环境下pip安装Python库
155 3
|
6月前
|
开发工具 git Python
安装和使用`libnum`是一个用于数字理论函数的Python库
【6月更文挑战第19天】`libnum`是Python的数字理论函数库。安装可通过`git clone`,进入目录后运行`python setup.py install`,也可用`pip install libnum`。示例:使用`int_to_hex`将十进制数42转换为十六进制字符串&#39;2a&#39;。注意,信息可能已过时,应查最新文档以确保准确性。如遇问题,参考GitHub仓库或寻求社区帮助。
129 1
|
5月前
|
Python
确保你已经安装了`python-barcode`库。如果没有,可以通过pip来安装:
确保你已经安装了`python-barcode`库。如果没有,可以通过pip来安装:
下一篇
DataWorks