[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

number of points to be plotted, and then multiplying by the point number; in case
you’ve forgotten too, it’s 360 degrees around the whole circle (e.g., if you plot 4 points
on a circle, each is 90 degrees from the last, or 360/4). Python’s standard math module
gives all the required constants and functions from that point forward—pi, sine, and
cosine. The math is really not too obscure if you study this long enough (in conjunction
with your old geometry text if necessary). There are alternative ways to code the number
crunching, but I’ll skip the details here (see the examples package for hints).


Even if you don’t care about the math, though, check out Example 11-11’s circle
function. Given the (X,Y) coordinates of a point on the circle returned by point, it draws
a line from the circle’s center out to the point and a small rectangle around the point
itself—not unlike the hands and points of an analog clock. Canvas tags are used to
associate drawn objects for deletion before each plot.


Example 11-11. PP4E\Gui\Clock\plotterGui.py


plot circles on a canvas


import math, sys
from tkinter import *


def point(tick, range, radius):
angle = tick (360.0 / range)
radiansPerDegree = math.pi / 180
pointX = int( round( radius
math.sin(angle radiansPerDegree) ))
pointY = int( round( radius
math.cos(angle * radiansPerDegree) ))
return (pointX, pointY)


def circle(points, radius, centerX, centerY, slow=0):
canvas.delete('lines')
canvas.delete('points')
for i in range(points):
x, y = point(i+1, points, radius-4)
scaledX, scaledY = (x + centerX), (centerY - y)
canvas.create_line(centerX, centerY, scaledX, scaledY, tag='lines')
canvas.create_rectangle(scaledX-2, scaledY-2,
scaledX+2, scaledY+2,
fill='red', tag='points')
if slow: canvas.update()


def plotter(): # 3.x // trunc div
circle(scaleVar.get(), (Width // 2), originX, originY, checkVar.get())


def makewidgets():
global canvas, scaleVar, checkVar
canvas = Canvas(width=Width, height=Width)
canvas.pack(side=TOP)
scaleVar = IntVar()
checkVar = IntVar()
scale = Scale(label='Points on circle', variable=scaleVar, from_=1, to=360)
scale.pack(side=LEFT)
Checkbutton(text='Slow mode', variable=checkVar).pack(side=LEFT)
Button(text='Plot', command=plotter).pack(side=LEFT, padx=50)


748 | Chapter 11: Complete GUI Programs

Free download pdf