#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : cp9_1_2.py
# @Author: WRH
# @Date : 2021/5/24
# @Edition:Python3.8.6
# 9.1.2 Canvas畫布上的函數圖形繪制
# 用create_line()方法可在畫布上繪制直線,而随着變量的變化,用該方法連續繪制微直線,即可得到函數的圖形
# 例9-6
'''
在窗體上建立320×240的畫布,以畫布中心為原點,用紅色繪制帶箭頭的x和y坐标軸,用藍色筆繪制正弦曲線y=sinx的函數圖形。
其中,x、y軸的放大倍數均為40倍,即:x=40t。t以0.01的步長在-π~π範圍内變化取值。
'''
import tkinter
import math
root = tkinter.Tk()
w = tkinter.Canvas(root, width=320, height=240)
w.pack()
w0=160 # 半寬
h0=120 # 半高
# 畫紅色的坐标軸線
w.create_line(0, 120, 320, 120, fill="red", arrow=tkinter.LAST)
w.create_line(160, 240, 160, 0, fill="red", arrow=tkinter.LAST)
# 标題文字
w.create_text(w0+50,10,text='y=sin(x)')
# x軸刻度
for i in range(-3,4):
j=i*40
w.create_line(j+w0, h0, j+w0, h0-5, fill="red")
w.create_text(j+w0,h0+5,text=str(i))
# y軸刻度
for i in range(-2,3):
j=i*40
w.create_line(w0, j+h0, w0+5, j+h0, fill="red")
w.create_text(w0-10,j+h0,text=str(-i))
# 計算x
def x(t):
x = t*40 # x軸放大40倍
x+=w0 # 平移x軸
return x
# 計算y
def y(t):
y = math.sin(t)*40 # y軸放大40倍
y-=h0 # 平移y軸
y = -y # y軸值反向
return y
# 連續繪制微直線
t = -math.pi
while(t<math.pi):
w.create_line(x(t), y(t), x(t+0.01), y(t+0.01),fill="blue")
t+=0.01
root.mainloop()
# 無論函數如何複雜,以“分而治之”的計算思維原則,分别調用x(t)和y(t)函數取值繪制微直線,即可最終獲得函數的圖形。
# 例9-7
'''
設定坐标原點(x0, y0)為畫布的中心(x0, y0分别為畫布寬、高的一半),以紅色虛線繪制坐标軸,并按以下公式繪制函數曲線:
x=(w0 /32)×(cost-tsint)
y=(h0 /32)×(sint+tcost)
式中,w0是畫布寬的一半,h0是畫布高的一半。t的取值範圍為0~25,步長為0.01。
'''
import tkinter
import math
root = tkinter.Tk()
w = tkinter.Canvas(root, width=600, height=600)
w.pack()
# 畫紅色的坐标軸線(虛線)
w.create_line(0, 300, 600, 300, fill="red", dash=(4, 4))
w.create_line(300, 0, 300, 600, fill="red", dash=(4, 4))
w0=300
h0=300
def x(t):
x = (w0 / 32) * (math.cos(t) - t*math.sin(t))
x+=w0 # 平移x軸
return x
def y(t):
y = (h0 / 32) * (math.sin(t) +t* math.cos(t))
y-=h0 # 平移y軸
y = -y # y軸值反向
return y
t = 0.0
while(t<25):
w.create_line(x(t), y(t), x(t+0.01), y(t+0.01),fill="blue")
t+=0.01
root.mainloop()