from tkinter import *
import math
WIDTH, HEIGHT = 510, 210
ORIGIN_X, ORIGIN_Y = 2, HEIGHT/2 #原点
SCALE_X, SCALE_Y = 40, 100 #x轴、y轴缩放倍数
ox, oy = 0, 0
x, y = 0, 0
arc = 0 #弧度
END_ARC = 360 * 2 #函数图形画两个周期
root = Tk()
c = Canvas(root, bg = 'white', width = WIDTH, height = HEIGHT)
c.pack()
c.create_text(200, 20, text = 'y = cos(x)')
c.create_line(0, ORIGIN_Y, WIDTH, ORIGIN_Y)
c.create_line(ORIGIN_X, 0, ORIGIN_X, HEIGHT)
for i in range(0, END_ARC+1, 10):
arc = math.pi * i / 180
x = ORIGIN_X + arc * SCALE_X
y = ORIGIN_Y - math.cos(arc) * SCALE_Y
c.create_line(ox, oy, x, y)
ox, oy = x, y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
直接执行返回 0 然后没有显示图片
在这里插入图片描述
2、解决办法
在最下面加一行代码:
root.mainloop()
1
完整代码如下:
from tkinter import *
import math
WIDTH, HEIGHT = 510, 210
ORIGIN_X, ORIGIN_Y = 2, HEIGHT/2 #原点
SCALE_X, SCALE_Y = 40, 100 #x轴、y轴缩放倍数
ox, oy = 0, 0
x, y = 0, 0
arc = 0 #弧度
END_ARC = 360 * 2 #函数图形画两个周期
root = Tk()
c = Canvas(root, bg = 'white', width = WIDTH, height = HEIGHT)
c.pack()
c.create_text(200, 20, text = 'y = cos(x)')
c.create_line(0, ORIGIN_Y, WIDTH, ORIGIN_Y)
c.create_line(ORIGIN_X, 0, ORIGIN_X, HEIGHT)
for i in range(0, END_ARC+1, 10):
arc = math.pi * i / 180
x = ORIGIN_X + arc * SCALE_X
y = ORIGIN_Y - math.cos(arc) * SCALE_Y
c.create_line(ox, oy, x, y)
ox, oy = x, y
root.mainloop()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
然后即可绘制出图片
在这里插入图片描述
3、原因
root到root.pack()之间,是设计的部件的类型,尺寸,样式,位置,然后绑定一个事件。mainloop就进入到事件(消息)循环。一旦检测到事件,就刷新组件。那是网上的说法,我的理解是如果没有mainloop,它也会绘图,但是绘图完成后就关闭了程序,所以就好像没有显示一样,加上mainloop后,它会监听你的行为,有关闭它才会结束程序
1、首先打开PyCharm软件,点击左上角的开始,打开一个Python项目。2、其次在Python项目中,新建并打开一个空白的python文件。
3、最后在python文件编辑区中,输入importrandom并导入random模块即可。
ImportError: No module named myModule这种错误就是说:模块不在搜索路径里,从而导致路径搜索失败!
导入模块时,不带模块的后缀名,比如.py
Python搜索模块的路径:
1)、程序的主目录
2)、PTYHONPATH目录(如果已经进行了设置)
3)、标准连接库目录(一般在/usr/local/lib/python2.X/)
4)、任何的.pth文件的内容(如果存在的话).新功能,允许用户把有效果的目录添加到模块搜索路径中去
.pth后缀的文本文件中一行一行的地列出目录。
这四个组建组合起来就变成了sys.path了,
>>>import sys