search
HomeBackend DevelopmentPython TutorialHow to draw graphs using the tkinter module in Python

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。tkinter模块(“Tk 接口”)是Python的标准Tk GUI工具包的接口。接下来通过本文给大家介绍Python中的tkinter模块作图教程,需要的朋友参考下

python简述:

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。自从20世纪90年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务和Web编程。Python[1]已经成为最受欢迎的程序设计语言之一。2011年1月,它被TIOBE编程语言排行榜评为2010年度语言。自从2004年以后,python的使用率是呈线性增长。

tkinter模块介绍

tkinter模块(“Tk 接口”)是Python的标准Tk GUI工具包的接口.Tk和Tkinter可以在大多数的Unix平台下使用,同样可以应用在Windows和Macintosh系统里.,Tk8.0的后续版本可以实现本地窗口风格,并良好地运行在绝大多数平台中。

由于Tkinter是内置到python的安装包中、只要安装好Python之后就能import Tkinter库、而且IDLE也是用Tkinter编写而成、对于简单的图形界面Tkinter还是能应付自如。

八、显示文字

用create_text在画布上写字。这个函数只需要两个坐标(文字x和y的位置),还有一个具名参数来接受要显示的文字。例如:

>>> from tkinter import*>>> tk = Tk()>>> canvas = Canvas(tk,width=400,height=400)>>> canvas.pack()>>> canvas.create_text(150,100,text='Happy birthday to you')

How to draw graphs using the tkinter module in Python

create_text函数还有几个很有用的参数,比方说字体颜色等。在下面的代码中,我们调用create_text函数时使用了坐标(130,120),还有要显示的文字,以及红色的填充色:

canvas.create_text(130,120,text='Happy birthday to you!',fill='red')

我们还可以指定字体,方法是给出一个包含字体名和字体大小的元组。例如大小为20的Times字体就是('Times',20):

>>> canvas.create_text(150,150,text='Happy birthday',font=('Times',15))>>> canvas.create_text(200,200,text='Happy birthday',font=('Courier',22))>>> canvas.create_text(220,300,text='Happy birthday',font=('Couried',30))

How to draw graphs using the tkinter module in Python

九、显示图片

要用tkinter在画布上显示图片,首先要装入图片,然后使用canvas对象上的create_image函数。

这是我存在E盘上的一张图片:

How to draw graphs using the tkinter module in Python

我们可以这样来显示one.gif图片:

>>> from tkinter import*>>> tk = Tk()>>> canvas = Canvas(tk,width=400,height=400)>>> canvas.pack()>>> my_image = PhotoImage(file='E:\\FFOutput\\one.gif')>>> canvas.create_image(0,0,anchor = NW,image = my_image) >>> canvas.create_image(50,50,anchor = NW,image = my_image)

在第五行中,把图片装入到变量my_image中。坐标(0,0)/(50,50)是我们要显示图片的位置, anchor=NW让函数使用左上角(northwest 西北方)作为画图的起始点,最后一个具名参数image指向装入的图片。

How to draw graphs using the tkinter module in Python

注:用tkinter只能装入GIF图片,也就是扩展名是.gif的图片文件。

想要显示其他类型的图片,如PNG和JPG,需要用到其他的模块,比如Python图像库。

十、创建基本的动画

创建一个填了色的三角形,让它在屏幕上横向移动:

import timefrom tkinter import*tk = Tk()canvas = Canvas(tk,width=400,height=200)canvas.pack()canvas.create_polygon(10,10,10,60,50,35) ##创建三角形for x in range(0,60): canvas.move(1,5,0) ##把任意画好的对象移动到把x和y坐标增加给定值的位置 tk.update()   ##强制tkinter更新屏幕(重画)   time.sleep(0.05) ##让程序休息二十分之一秒(0.05秒),然后再继续

三角形横向移动

延伸一下,如果想让三角形沿对角线在屏幕上移动,我们可以第8行为:

import timefrom tkinter import*tk = Tk()canvas = Canvas(tk,width=400,height=400)canvas.pack()canvas.create_polygon(10,10,10,60,50,35) ##创建三角形for x in range(0,60): canvas.move(1,5,5) ##把任意画好的对象移动到把x和y坐标增加给定值的位置 tk.update()   ##强制tkinter更新屏幕(重画)   time.sleep(0.05) ##让程序休息二十分之一秒(0.05秒),然后再继续

三角形沿对角线移动

如果要让三角形在屏幕上沿对角线回到开始的位置,要用-5,-5(在结尾处加上这段代码)

import timefrom tkinter import*tk = Tk()canvas = Canvas(tk,width=400,height=400)canvas.pack()canvas.create_polygon(10,10,10,60,50,35) ##创建三角形for x in range(0,60): canvas.move(1,5,5) ##把任意画好的对象移动到把x和y坐标增加给定值的位置 tk.update()   ##强制tkinter更新屏幕(重画)   time.sleep(0.05) ##让程序休息二十分之一秒(0.05秒),然后再继续for x in range(0,60): canvas.move(1,-5,-5)  tk.update()     time.sleep(0.05)

对角线运动并回到初始位置

十一、让对象对操作有反应

我们可以用“消息绑定”来让三角形在有人按下某键时有反应。

要开始处理事件,我们首先要创建一个函数。当我们告诉tkinter将某个特定函数绑到(或关联到)某个特定事件上时就完成了绑定。

换句话说,tkinter会自动调用这个函数来处理事件。

例如,要让三角形在按下回车键时移动,我们可以定义这个函数:

def movetriangle(event): canvas.move(1,5,0)

这个函数只接受一个参数(event),tkinter用它来给函数传递关于事件的信息。现在我们用画布canvas上的bind_all函数来告诉tkinter当特定事件发生时应该调用这个函数。代码如下:

from tkinter import*tk = Tk()canvas = Canvas(tk,width=400,height=400)canvas.pack()canvas.create_polygon(10,10,10,60,50,35)def movetriangle(event): canvas.move(1,5,0)canvas.bind_all(&#39;<KeyPress-Return>&#39;,movetringle) ##让tkinter监视KeyPress事件,当该事件发生时调用movetriangle函数

那么我们如何根据按键的不同而改变三角形的方向呢?比如用方向键。

我们可以尝试改下movetriangle函数:

def movetriangle(event): if event.keysym == &#39;up&#39;:  canvas.move(1,0,-3) ##第一个参数使画布上所画的形状的ID数字,第二个是对x(水平方向)坐标增加的值,第三个是对y(垂直方向)坐标增加的值 elif event.keysym == &#39;down&#39;:  canvas.move(1,0,3) elif event.keysym == &#39;left&#39;:  canvas.move(1,-3,0) else  canvas.move(1,3,0)

最后代码汇总在一起为:

from tkinter import*tk = Tk()canvas = Canvas(tk,width=400,height=400)canvas.pack()canvas.create_polygon(10,10,10,60,50,35)def movetriangle(event): if event.keysym == &#39;Up&#39;:  canvas.move(1,0,-3) ##第一个参数使画布上所画的形状的ID数字,第二个是对x(水平方向)坐标增加的值,第三个是对y(垂直方向)坐标增加的值 elif event.keysym == &#39;Down&#39;:  canvas.move(1,0,3) elif event.keysym == &#39;Left&#39;:  canvas.move(1,-3,0) else:  canvas.move(1,3,0)canvas.bind_all(&#39;<KeyPress-Up>&#39;,movetriangle) ##让tkinter监视KeyPress事件,当该事件发生时调用movetriangle函数canvas.bind_all(&#39;<KeyPress-Down>&#39;,movetriangle)canvas.bind_all(&#39;<KeyPress-Left>&#39;,movetriangle)canvas.bind_all(&#39;<KeyPress-Right>&#39;,movetriangle)

方向键控制三角形的移动

十二、更多使用ID的方法

只要用了画布上面以create_开头的函数,它总会返回一个ID。这个函数可以在其他的函数中使用。

如果我们修改代码来把返回值作为一个变量保存,然后使用这个变量,那么无论返回值是多少,这段代码都能工作:

>>> mytriangle = canvas.create_polygon(10,10,10,60,50,35)>>> canvas.move(mytriangle,5,0)

我们可以用itemconfig来改变三角形的颜色,这需要把ID作为第一个参数:

>>> canvas.itemconfig(mytrigle,fill=&#39;bue&#39;) ##把ID为变量mytriangle中的值的对象的填充颜色改为蓝色

也可以给三角形一条不同颜色的轮廓线,同样适用ID作为第一个参数:

>>> canvas.itemconfig(mytrigle,outline=&#39;red&#39;)

总结做出了简单的动画。学会了如何用事件绑定来让图形响应按键,这在写计算机游戏时很有用。在tkinter中以create开头的函数是如何返回一个ID数字。

已经学习Python两天,最开始是想着是通过觉得用它写个动画或者画个图形比较方便,而且界面美观,比黑洞洞的dos窗口好多了,准备写个程序送个一女孩作为生日礼物(去年答应好的)。经过这两天的学习,我慢慢发觉了Python语言的优点,其最主要的就是易学,而且可以调用各种库。

以上所述是小编给大家介绍的How to draw graphs using the tkinter module in Python,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多How to draw graphs using the tkinter module in Python相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.