我有一个问题,我无法从导入的模块中导入变量。
from Turtle import Turtle
from Turtle import *
from PIL import Image
import random
f = open("Lab11Data.txt", "w")
img=Image.new('RGB',(640,480),(255,255,255))
for i in range(800):
global newPixels
t = Turtle(img,320,450,90,(0,0,0))
n = 50
for i in range(9):
t.move(n)
x = random.randint(1,2)
if x == 1:
t.turn(15)
if x == 2:
t.turn(-15)
n-=1
f.write(str(newPixels))
f.write("\n")
img.save("Lab11Image.png")
我已经导入了模块Turtle(不是python的turtle),并且我试图从那里使用一个变量。
from PIL import Image
from math import sin, cos, pi
class Turtle:
def __init__(self, im, x = 0, y = 0, deg = 0, color = (0, 0, 0)):
self.im = im
self.x = x
self.y = y
self.deg = deg
self.color = color
def turn(self, degs):
self.deg = (self.deg + degs) % 360
def move(self, dist):
newPixels = 0
i = 0
while i < dist:
if self.im.getpixel((int(self.x), int(self.y))) != self.color:
self.im.putpixel((int(self.x), int(self.y)), self.color)
newPixels += 1
self.x += cos(self.deg * pi / 180)
self.y -= sin(self.deg * pi / 180)
i += 1
return newPixels
我不断收到一个名称错误,提示未定义相关的变量。 错误:
Traceback (most recent call last):
File "Lab11.py", line 20, in <module>
f.write(str(newPixels))
NameError: global name 'newPixels' is not defined