def plot(result, blocks, name): scale = 400 turtle.hideturtle() turtle.tracer(False) turtle.speed("fast") turtle.clear() turtle.penup() turtle.home() turtle.goto(-scale, scale) # 左上角 turtle.pendown() turtle.forward(scale * 2) # 右上角 turtle.right(90) # 向下 turtle.forward(scale * 2) # 右下角 turtle.right(90) # 向左 turtle.forward(scale * 2) # 左下角 turtle.right(90) # 向上 turtle.forward(scale * 2) # 左上角 block_radius = 4 for block in blocks: turtle.penup() turtle.goto(block.x * scale + block_radius, block.y * scale) turtle.pendown() turtle.begin_fill() turtle.circle(block_radius) turtle.end_fill() for circle in result: turtle.penup() turtle.goto((circle.x + circle.r) * scale, circle.y * scale) turtle.pendown() turtle.circle(circle.r * scale) ts = turtle.getscreen().getcanvas() canvasvg.saveall(name + ".svg", ts) turtle.hideturtle()
def saveImg(): print("Done.") save = input("Would you like to save this tree? Y/N \n") if save.upper() == "Y": t.hideturtle() name = input("What would you like to name it? \n") nameSav = name + ".svg" ts = turtle.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) elif save.upper() == "N": def runChk(): runAgain = input("Would you like to run again? Y/N (N will exit)") if runAgain.upper() == "Y": print("Running") main() elif runAgain.upper() == "N": print("Exiting...") exit() else: print("Invalid response.") runChk() runChk() else: print("Invalid response.") saveImg()
def map2d(): canvasvg.saveall("image.svg", move.getscreen().getcanvas()) ts = move.getscreen() ts.getcanvas().postscript(file='turtle.eps', colormode='color') img = Image.open("turtle.eps") img.save("test.png", "png") os.remove("turtle.eps")
def main(): rule_num = 1 f = open("LSystemsCode.txt", "r", encoding='utf-8') lines = f.readlines() grammar = Grammar(lines) for rule in grammar.rules: key, value = rule.split("->") SYSTEM_RULES[key.strip()] = value.strip() rule_num += 1 axiom = grammar.axiom iterations = grammar.steps model = derivation(axiom, iterations) segment_length = 5 alpha_zero = 90 angle = grammar.angle r_turtle = set_turtle(alpha_zero) turtle_screen = turtle.Screen() turtle_screen.screensize(1500, 1500) draw_l_system(r_turtle, model[-1], segment_length, angle, grammar.alfabet) ts = turtle.getscreen().getcanvas() canvasvg.saveall("LSystem.svg", ts, None, 10, None) turtle_screen.exitonclick()
def save(fn): turtle.hideturtle() ts = turtle.getscreen().getcanvas() canvasvg.saveall(fn, ts) turtle.reset() turtle.width(3) turtle.speed(100)
def main(): rule_num = 1 f = open("LSystemsCode.txt", "r", encoding='utf-8') lines = f.readlines() gramatica = Gramatica(lines) for regra in gramatica.regra: key, value = regra.split("->") SYSTEM_RULES[key.strip()] = value.strip() rule_num += 1 axioma = gramatica.axioma iterations = gramatica.passos model = div(axioma, iterations) segment_length = 5 alpha_zero = 90 angulo = gramatica.angulo r_turtle = set_turtle(alpha_zero) turtle_screen = turtle.Screen() turtle_screen.screensize(1500, 1500) desenho_1(r_turtle, model[-1], segment_length, angulo, gramatica.alfabeto) ts = turtle.getscreen().getcanvas() canvasvg.saveall("LSystem.svg", ts, None, 10, None) turtle_screen.exitonclick()
def main(): num_regra = 4 f = open("Definicoes.txt", "r", encoding='utf-8') linhas = f.readlines() gramatica = Gramatica(linhas) for regra in gramatica.regras: key, value = regra.split("->") regrasDoSistema[key.strip()] = value.strip() num_regra += 1 axioma = gramatica.axioma iteracoes = gramatica.reps modelo = derivacao(axioma, iteracoes) comprimentoLinha = 8 anguloInicial = 60 angulo = gramatica.angulo r_turtle = set_turtle(anguloInicial) turtle_screen = turtle.Screen() turtle_screen.screensize(2000, 2000) desenha(r_turtle, modelo[-1], comprimentoLinha, angulo, gramatica.alfabeto) ts = turtle.getscreen().getcanvas() canvasvg.saveall("Imagem.svg", ts, None, 10, None) turtle_screen.exitonclick()
def draw(): polygon = turtle.Turtle() screen = turtle.Screen() polygon.hideturtle() turtle.colormode(255) for i in range(1000): change_color = random.randint(0,1) if change_color == 0: polygon.pencolor((random.randint(0,255),random.randint(0,255),random.randint(0,255))) polygon.down() polygon.forward(random.randint(-100,100)) polygon.right(90) polygon.forward(random.randint(-100,100)) polygon.right(90) polygon.forward(random.randint(-100,100)) polygon.right(90) polygon.forward(random.randint(-100,100)) polygon.right(90) polygon.hideturtle() nameSav = "prova.svg" ts = turtle.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) drawing = svg2rlg("prova.svg") renderPM.drawToFile(drawing, "prova.png", fmt="PNG")
def plot(result, name): scale = 400 turtle.tracer(False) turtle.speed("fast") turtle.clear() turtle.penup() turtle.home() turtle.goto(-scale, scale) # 左上角 turtle.pendown() turtle.forward(scale * 2) # 右上角 turtle.right(90) # 向下 turtle.forward(scale * 2) # 右下角 turtle.right(90) # 向左 turtle.forward(scale * 2) # 左下角 turtle.right(90) # 向上 turtle.forward(scale * 2) # 左上角 # print "len = ", len(result) for circle in result: # print circle.x, circle.y, circle.r turtle.penup() turtle.goto((circle.x + circle.r) * scale, circle.y * scale) turtle.pendown() turtle.circle(circle.r * scale) ts = turtle.getscreen().getcanvas() canvasvg.saveall(name + ".svg", ts)
def saveImg(): print("Done.") save = raw_input("Would you like to save this tree? Y/N \n") if save.upper() == "Y": turtle.hideturtle() name = raw_input("What would you like to name it? \n") nameSav = name + ".svg" ts = turtle.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) elif save.upper() == "N": def runChk(): runAgain = raw_input( "Would you like to run again? Y/N (N will exit)") if runAgain.upper() == "Y": print("Running") random_fractal() elif runAgain.upper() == "N": print("Exiting...") exit() else: print("Invalid response.") runChk() runChk() else: print("Invalid response.") saveImg()
def cliqueSalvar(self, event): tkMessageBox.showinfo("Informacao", "Verifique o terminal") self.nomeArquivo = raw_input("Digite o nome da imagem: ") self.ts = self.mapa.getscreen().getcanvas() canvasvg.saveall(self.nomeArquivo + ".svg", self.ts) tkMessageBox.showinfo( "Informacao", "Imagem [" + self.nomeArquivo + ".svg]" + " salvo com sucesso!")
def draw(dir, name): turtle.hideturtle() polygon = turtle.Turtle() screen = turtle.Screen() turtle.bgcolor("black") polygon.speed(0) polygon.hideturtle() turtle.colormode(255) x = 0.01 a = 0 b = 0 c = 255 change_dir = 0 for j in range(1000): if j >= 765: i = j - 765 else: i = j if i < 255: polygon.pencolor(a, 0, c) a += 1 c -= 1 elif 255 <= i < 510: polygon.pencolor(a, b, 0) b += 1 a -= 1 else: polygon.pencolor(0, b, c) c += 1 b -= 1 polygon.circle(10 + x * 10) if change_dir == 0: polygon.forward(1 + x) else: polygon.backward(1) polygon.backward(1) if j % 10 == 0: polygon.rt(90) x += 0.01 polygon.hideturtle() nameSav = os.path.join(dir, "{}.svg".format(name)) polygon.hideturtle() ts = turtle.getscreen().getcanvas() polygon.hideturtle() canvasvg.saveall(nameSav, ts) drawing = svg2rlg(os.path.join(dir, "{}.svg".format(name))) renderPM.drawToFile(drawing, os.path.join(dir, "{}.png".format(name)), fmt="PNG")
def save(self): """Save plot in svg""" settings = { "parent": self.frame, "defaultextension": ".svg", "initialfile": "graph.svg", "title": "Save graph" } file = tkinter.filedialog.asksaveasfilename(**settings) canvasvg.saveall(file, self.canvas)
def callback(self, event): # print("callback:", event) old_generation = self.generation if event.char == '+' or event.keysym == 'Right': if self.generation < self.fractale.max: self.generation += 1 elif event.char == '-' or event.keysym == 'Left': if self.generation > 0: self.generation -= 1 elif event.char == 'r': self.crt.repere() elif event.char == 'u': old_generation = None elif event.char == '0': old_generation = None self.generation = 0 elif event.char == 'v': self.details = not self.details old_generation = None elif event.char == 's': self.lisser = not self.lisser old_generation = None elif event.keysym == 'Next': self.continuer = 1 self.crt.root.quit() elif event.keysym == 'Prior': self.continuer = -1 self.crt.root.quit() elif event.char == 'x' or event.char == 'q': self.crt.root.quit() elif event.char == 'h': mbox.showinfo("Fractales", """ h \t: cette aide x, q \t: sortir + / → \t: avancer d'une génération - / ← \t: reculer d'une génération 0 \t: génération 0 (graine) v \t: voir les points de construction r \t: tracer le repère et afficher X,Y u \t: rafraîchir l'affichage s \t: lisser la courbe p \t: sauver le dessin en PostScript """) elif event.char == 'p': self.sauve() elif event.char == 'P': self.auto_sauve = not self.auto_sauve self.sauve() elif event.char == 'w': print("export en .svg") canvasvg.saveall("canvas.svg", self.crt.canvas) if self.generation != old_generation: self.dessine()
def saveImg(): save = str(raw_input("Would you like to save this image?(Y/N)\n")) if save.upper() == "Y": turtle.hideturtle() name = str(raw_input("What would you like to name it? \n")) nameSav = name + ".svg" if os.path.isdir("Automaton Drawings") == False: os.mkdir("Automaton Drawings") os.chdir("Automaton Drawings") ts = turtle.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) cairosvg.svg2png(url=nameSav, write_to=name + ".png")
def save_art(): file_name = date_time_to_string() file_name1 = str(file_name) infile = "art_saves/" + file_name1 saveall(infile + ".svg", wn.getcanvas(), items=None, margin=10, tounicode=None) creat_html(file_name)
def saveimage(): import os import shutil import tempfile import canvasvg from tkinter import filedialog ts = turtle.getscreen().getcanvas() filename = filedialog.asksaveasfilename() + ".svg" canvasvg.saveall(filename, ts) return
def viz_circle(self, sstr, seq): """ Returns svg of chord secondary structure graph """ # Create a Tk instance master = Tk() master.title("Chord Diagram") master.resizable(width = 0, height = 0) # Create canvas canvaswidth = 600 canvasheight = 600 w = Canvas(master, width = canvaswidth, height = canvasheight) w.pack() w.configure(background = "white") # Toggle base name display display_bases = True if len(seq) > 100: display_bases = False # Draw circle and tick marks w.create_oval(50, 50, 550, 550) angle = (2 * math.pi) / len(seq) # Draw bases and tick marks coords = [] for i, base in enumerate(seq): theta = i * angle # Draw bases r = 275 x = r * math.cos(theta) + (canvaswidth / 2) y = r * math.sin(theta) + (canvasheight / 2) if display_bases: w.create_text(x, y, text = base) r = 250 x2 = r * math.cos(theta) + (canvaswidth / 2) y2 = r * math.sin(theta) + (canvasheight / 2) w.create_oval(x2 - 2, y2 - 2, x2 + 2, y2 + 2, fill = "black", activewidth = 4) # Save base location coords.append({"x": x2, "y": y2}) # Draw segments between bases for base1, base2 in sstr: w.create_line(coords[base1]["x"], coords[base1]["y"], coords[base2]["x"], coords[base2]["y"], fill = "red") # Output to file canvasvg.saveall("circle.svg", w)
def save(self, filename: str): ''' Save the window as png. :param filename: filename TODO: Cannot save background color for a while. ''' import canvasvg import cairosvg screen = self.getscreen().getcanvas() svgname = ''.join([filename, '.svg']) pngname = ''.join([filename, '.png']) canvasvg.saveall(svgname, screen) cairosvg.svg2png(url=svgname, write_to=pngname)
def create_shape(nom,size,color,date): turtle.screensize(2000,2000) turtle.speed("fastest") turtle.penup() radius = 250+(size*30) malwarename=nom.split('_') namem=malwarename[0] turtle.right(90) # Face South turtle.forward(radius/4-75) # Move one radius turtle.right(270) turtle.write(namem, move=False, align="center", font=("Arial", int(80+size), "bold")) turtle.home() turtle.right(90) # Face South turtle.forward(radius/3+75) # Move one radius turtle.right(270) turtle.write(date, move=False, align="center", font=("Arial", int(80), "bold")) turtle.home() turtle.pensize(15) turtle.right(90) # Face South turtle.forward(radius) # Move one radius turtle.right(270) turtle.pendown() turtle.circle(radius) turtle.penup() # Pen up while we go home turtle.home() for c,d in color.items(): radius+=75 turtle.right(90) # Face South turtle.forward(radius) # Move one radius turtle.right(270) # Back to start heading turtle.pencolor(c) turtle.pendown() # Put the pen back down if d == True : dashed_circle(radius) else: turtle.circle(radius) turtle.penup() # Pen up while we go home turtle.home() turtle.hideturtle() svg = nom+".svg" png = nom+".png" print("svg ="+svg) print("png ="+png) ts = turtle.getscreen().getcanvas() canvasvg.saveall(svg, ts) cmd="cairosvg "+svg+" -o "+png os.system(cmd) turtle.reset()
def RenderSVG(self, SceneName): self.t.hideturtle() if self.PrevName == SceneName: nameSav = SceneName + str(self.renderCount) + ".svg" ts = self.t.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) self.renderCount += 1 self.PrevName = SceneName else: self.renderCount = 1 nameSav = SceneName + str(self.renderCount) + ".svg" ts = self.t.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) self.renderCount += 1 self.PrevName = SceneName self.t.showturtle()
def draw_bar(dataset,title,scale,maxima): turt = turtle.Turtle() turt.setpos(300,0) window = turtle.Screen() window.colormode(255) turt.speed(700) max = 0 for y in dataset: if y > max: max = y turt.left(180) turt.forward(600) turt.right(90) turt.forward(300) turt.pd() turt.left(180) turt.forward(300) write_range(dataset,turt,scale,300/maxima) # draw dataset for data in dataset: turt.fillcolor(((data[0]*8)%255,(data[0]*8/30)%255,(data[0]*8)%255)) turt.forward(30) write_val(data[1],turt) turt.begin_poly() turt.begin_fill() turt.left(90) turt.forward(data[0]*300/maxima) turt.right(90) turt.forward(60) turt.right(90) turt.forward(data[0]*300/maxima) turt.end_poly() turt.end_fill() turt.left(90) turt.penup() turt.forward(300-len(dataset)*90+100) turt.right(90) turt.forward(150) turt.right(90) turt.forward(50) turt.left(180) turt.write(title,True,"center",("serif",32,"bold")) nameSav = title+".svg" ts = turt.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) window.exitonclick()
def make_photo(index): T.speed(0) T.setup(width=100, height=100, startx=0, starty=0) for x in range(4): # print(T.xcor()) coord = (randint(-50, 50), randint(-50, 50)) # print(coord) T.goto(coord) T.hideturtle() ts = T.getscreen().getcanvas() canvasvg.saveall("image.svg", ts) T.clear() script = "convert -size 100x100 image.svg images/square_" + str( index) + ".png" os.system(script) os.system("rm image.svg")
def viz_arc(self,sstr,seq): """ Returns svg of arc secondary structure graph """ # Create Tk instance master = Tk() master.title("Arc Diagram") master.resizable(width=0, height=0) # Create canvas canvasw = max(min((len(seq)*8),1024), 600) canvash = max(min((len(seq)*2.25),768), 200) w = Canvas(master, width = canvasw, height = canvash) w.pack() # Toggle base name display display_bases = True if len(seq) > 100: display_bases = False # Draw line and tick marks w.create_line(50,canvash-50,canvasw-50,canvash-50) l = len(seq) spacer = (canvasw-100)/(l-1) coords = [] for i,base in enumerate(seq): x = (spacer * i) + 50 y = canvash-50 w.create_line(x, y+4, x, y-4) if display_bases: w.create_text(x, y+16 , text = base) coords.append({"x":x, "y": y}) # Draw segments between bases for base1, base2 in sstr: w.create_arc(coords[base1]["x"], coords[base1]["y"] - (base2-base1)*2.5, coords[base2]["x"], coords[base2]["y"] + (base2-base1)*2.5, start = 0, extent = 180, style = "arc") # Output to file canvasvg.saveall("arc.svg", w)
def export(): import canvasvg, os for node in Node.registry.values(): if len(node._edges) == 2: if sum(node._edges.keys()) == 0 or sum( node._edges.keys()) == 180: x = node.x + self.master.coordinate_plane.width // 2 y = self.master.coordinate_plane.height // 2 - node.y self.master.coordinate_plane.itemconfigure( self.master.coordinate_plane.find_enclosed( x + 4, y + 4, x - 4, y - 4)[0], state='hidden') canvasvg.saveall( os.path.abspath( os.path.join(self.export_dir.get(), self.export_filename.get() + '.svg')), maze.coordinate_plane)
def draw(): turtle.hideturtle() polygon = turtle.Turtle() screen = turtle.Screen() turtle.bgcolor("black") polygon.speed(0) polygon.hideturtle() turtle.colormode(255) x = 0 a = 0 b = 0 c = 255 for i in range(1000): if i >= 765: i = i - 765 if i < 255: polygon.pencolor(a, 0, c) a += 1 c -= 1 elif 255 <= i < 510: polygon.pencolor(a, b, 0) b += 1 a -= 1 else: polygon.pencolor(0, b, c) c += 1 b -= 1 polygon.fd(10 + x) polygon.rt(90.7) x += 0.7 polygon.hideturtle() nameSav = "prova.svg" polygon.hideturtle() ts = turtle.getscreen().getcanvas() polygon.hideturtle() canvasvg.saveall(nameSav, ts) drawing = svg2rlg("prova.svg") renderPM.drawToFile(drawing, "prova.png", fmt="PNG")
def gen_turtle(): result_png = os.path.join(BASE_PATH, 'turtle.png') if os.path.exists(result_png): return True turtle.ht() turtle.color("purple") turtle.pensize(2) turtle.goto(4, 8) turtle.goto(8, 0) turtle.goto(0, 0) ts = turtle.getscreen() ts = turtle.getscreen().getcanvas() tmpfile = 'xx_tmp.svg' canvasvg.saveall(tmpfile, ts) with open(tmpfile) as svg_input, open(result_png, 'wb') as png_output: cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
def drawSpiral(angle_start=90,angle_ratio=0,step_start=50,step_ratio=0.1): colors = ['navy','red','purple','blue','green','magenta','yellow'] while (angle_start!=0): angle_start=int(input("Starting Angle? Concave>90: ")) step=step_start angle=angle_start step_delta= step_start*step_ratio angle_delta=angle_start*angle_ratio clearscreen() bgcolor("black") tracer(0,0) t=Pen() for x in range(20): t.color(random.choice(colors)) t.forward(step) t.left(angle) step+=step_delta angle+=angle_delta update() canvasvg.saveall("spiral.svg",Screen()._canvas) exitonclick()
import canvasvg def thing(): turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(50) turtle.right(90) turtle.forward(50) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(25) turtle.right(90) turtle.forward(25) turtle.right(90) turtle.forward(50) turtle.hideturtle() turtle.speed() for i in range(15): thing() turtle.right(10) turtle.forward(50) ts = turtle.getscreen() canvas = ts.getcanvas() canvasvg.saveall("example1.svg", canvas) #ts.getcanvas().postscript(file="example1.svg")
def main(): size = 5 global COLORS # Initialization: check for loadable file print("Hello. Welcome to lsys.") if (len(sys.argv) >= 2): filename = sys.argv[1] # NOTE: command line filename will be relative to shell, not file lsysCollection = loadLsysFromFile(filename) else: lsysCollection = [] try: lsysCollection = loadLsysFromFile(DEFAULT_DATA_FILE) except FileNotFoundError: print( "No file was loaded. Use 'load [filename]' to parse a file for lsys objects." ) # User input loop while True: # Prompt, extract command term and params userIN = input("lsys>").lower().strip(" ").split(" ") cmdTerm = userIN[0] if (len(userIN) >= 2): param = userIN[1] else: param = None if 'help'.startswith(cmdTerm): printHelp() if 'colors'.startswith(cmdTerm): if COLORS == None: print("No colors are loaded.") else: print(COLORS) elif 'display'.startswith(cmdTerm): display(param, lsysCollection) elif 'size'.startswith(cmdTerm): if not param.isdigit(): print("Invalid use of 'size'. Usage \'size [int]\'") else: size = int(param) print("Size has been set to {}.".format(size)) elif 'run'.startswith(cmdTerm): obj = getLsysFromCollection(lsysCollection, param) if obj == None: # Check if object was found print( "Could not find an lsys w/ name/number '{}'".format(param)) else: print("Using the lsys called {}.".format(obj.name)) try: n = int(userIN[2]) runLsys(obj, n, size) except ValueError: print( "Error: The number of iterations must be a non-negative integer. Aborting..." ) except IndexError: print( "Error: # of iterations not given. Usage: 'run [lsys_name/num] [#_of_iterations]'" ) except t.Terminator: # NOTE Don't touch this; program will crash on closing turtle window NOTE # F**k it, run it again - it seems to work runLsys(obj, n, size) elif 'runthru'.startswith(cmdTerm): obj = getLsysFromCollection(lsysCollection, param) if obj == None: # Check if object was found print( "Could not find an lsys w/ name/number '{}'".format(param)) else: print("Using the lsys called {}.".format(obj.name)) try: for i in range(int(userIN[2]), int(userIN[3])): runLsys(obj, i, size) if input("ENTER to continue. 'X' to quit.").upper( ) == "X": break except ValueError: print( "Error: Invalid params for runthru range. Params must be integers." ) elif 'save'.startswith(cmdTerm): try: ts = t.getscreen().getcanvas() dir = os.path.dirname(__file__) filename = "images/{}_{}_{}.svg".format( obj.name, str(n), str(datetime.date.today())) canvasvg.saveall(os.path.join(dir, filename), ts) # Save as svg except NameError: print( "The canvasvg module was not imported. You must install it to save images. \ Run 'pip install canvasvg'") except t.Terminator: print( "The turtle canvas must be open to save the image. You must re-run your command to save." ) elif 'load'.startswith(cmdTerm): if param == None: print("Invalid use of 'load'. Usage \'load [filename]\'") else: try: lsysCollection += getLsysFromFile(param) print("Sucessfully loaded: {}. \ Use 'display' to see the updated list of lsys objects." .format(param)) except FileNotFoundError: print("Error: File was not found: {}.".format(param)) except IndexError: print("Error: Invalid syntax in datafile.") elif 'exit'.startswith(cmdTerm) or 'quit'.startswith(cmdTerm): exit() elif 'dump'.startswith(cmdTerm): if "yes".startswith( input( "Are you sure you'd like to dump currently loaded collection? (y/n) " ).lower()): lsysCollection = list() print("Done.") elif 'mod'.startswith(cmdTerm): l = getLsysFromCollection(lsysCollection, param) try: attr = userIN[2].lower() if attr == 'angle': l.angle = (float(userIN[3])) elif attr == 'axiom': l.axiom = (userIN[3]) print("Set the {} of {} to be {}".format( attr, l.name, userIN[3])) except ValueError: print( "Error: Invalid attribute. Attribute must be float for angle." ) except IndexError: print( "Error: Invalid number of arguments. Usage 'mod [lsys_name] [lsys_attr] [new_attr_val]'" ) except AttributeError: print("Error: No lsys objects are currently loaded.") elif cmdTerm == '': pass else: print("Unknown command: {}".format(cmdTerm))
import canvasvg from canvasvg import saveall import turtle turtle.forward(100) for mode in [canvasvg.PYTHON, canvasvg.MODULE, canvasvg.NONE]: print("warning mode = %d\n" % mode) canvasvg.warnings(mode) saveall('turtlepower.svg', turtle.getscreen().getcanvas())
start_angle= -90 - angle/2 t.up() t.goto(x+radius*math.cos(math.pi/180*start_angle),y+radius*math.sin(math.pi/180*start_angle)) t.down() t.seth(90) for x in range(0,sides): t.forward(step) t.left(angle) turtle.clearscreen() turtle.tracer(0,0) canvas=500 # sides = input('# of sides?') # radius = input('radius?') sides = [3,4,5,6,8,10,36] colors = ['navy','red','purple','blue','green','magenta','yellow'] dictionary = dict(zip(sides,colors)) print(dictionary) radius=canvas/5 turtle.setup(canvas,canvas,0,0) t=turtle.Pen() for side,color in dictionary.items(): t.color(color) drawPolygon (t,0,0,side,radius) turtle.update() canvasvg.saveall("polygon.svg",turtle.Screen()._canvas) turtle.exitonclick()
for c in colors: p.pu() p.goto(dotx[i], doty[i]) p.pd() p.color(c) p.circle(R, 360) i += 1 R = 30 x = 0 - 2 * R y = 100 if __name__ == "__main__": wuhuan(R, x, y) import canvasvg canvasvg.saveall("wuhuan.svg", p.getscreen().getcanvas()) #old code: p.pu() p.goto(0, 0) p.pd() p.color("blue") p.circle(R, 360) p.pu() p.goto(2 * R, 0) p.pd() p.color("black") p.circle(R, 360) p.pu() p.goto(4 * R, 0) p.pd()
singlecolor(t4, colorchart[3]) singlecolor(t5, colorchart[4]) length = 1 #uncomment for new pattern each reset #newseed = pickseed() else: pickrandom(each, length, degrees, newseed) length += 1 #if pattern gets too long, moves to random location and rests length if length >= total: xThis = random.randrange(resXlow, resXhigh) yThis = random.randrange(resYlow, resYhigh) moveto(t1, xThis, yThis, 0) moveto(t2, xThis, yThis, 0) moveto(t3, xThis, yThis, 0) moveto(t4, xThis, yThis, 0) moveto(t5, xThis, yThis, 0) length = 1 timestamp = time.strftime('%y%j%I%H%M%S') newname = '' for each in newseed: newname += each canvasvg.saveall(newname + timestamp + ".svg", turtle.getcanvas()) print('saved ' + newname + timestamp + '.svg') print('fin') #turtle.mainloop() os.kill(os.getppid(), signal.SIGHUP)
def save_to_disk(self, event): canvasvg.saveall('canvas.svg', self.canvas)
def save_output(): canvas = turtle.getscreen().getcanvas() canvasvg.saveall('recaman.svg', canvas)
def handleClick(self, x, y): """ determine if button was clicked on, if so save canvas to .svg """ if x >= 150 and x <= 300 and y >= 340 and y <= 380: canvasvg.saveall(self.name+".svg", self.globwin._canvas) print("Graph saved to .svg file! Check the Graphable directory.")
def handleClick(self, x, y): """ determine if button was clicked on, if so save canvas to .svg """ if x >= 150 and x <= 300 and y >= 340 and y <= 380: canvasvg.saveall(self.name + ".svg", self.globwin._canvas) print("Graph saved to .svg file! Check the Graphable directory.")
t.forward(step) t.left(obstuse_angle) # Set Initial Parameters canvas=500 #sides = input('# of rhombus?') #side = input('length?') sides = 10 center_angle=360/sides acute_angle=center_angle*3/2 colors = ['navy','red','purple','blue','green','magenta','yellow'] side=canvas/5 # Start Turtle turtle.clearscreen() turtle.setup(canvas,canvas,0,0) turtle.bgcolor("black") turtle.tracer(0,0) #turtle.speed(10) t=turtle.Pen() for x in range(sides): t.color(random.choice(colors)) drawRhombus(t,side,acute_angle) t.left(center_angle) turtle.update() canvasvg.saveall("snowflake.svg",turtle.Screen()._canvas) turtle.exitonclick()
def save(self): canvas = tr._getscreen().getcanvas() canvasvg.saveall(self.generate_name() + self.extension, canvas)
def save_as_svg(canvas, file_name, colormode='color', width=None): """ Width is ignored for SVG images; colormode is currently ignored. """ canvasvg.saveall(file_name, canvas, items=canvas.find_withtag(Tk_.ALL))
def savesvg(t,filename): import canvasvg canvasvg.saveall(filename, t.getscreen().getcanvas())
#尾巴 t.pensize(4) t.color((255, 155, 192)) t.pu() t.seth(90) t.fd(70) t.seth(0) t.fd(95) t.pd() t.seth(0) t.circle(70, 20) t.circle(10, 330) t.circle(70, 30) t.forward(10) ts = t.getscreen() #ts.getcanvas().postscript(file="work.eps") #.eps文件即postscript脚本 #name = raw_input("输入文件名\n") nameSav = "ceshi.png" tmpdir = tempfile.mkdtemp() # 创建临时文件夹 tmpfile = os.path.join(tmpdir, r'c:/Users/Administrator/Desktop/tmp.svg') # SVG文件 tb = ts.getcanvas() canvasvg.saveall(tmpfile, tb) with open(tmpfile) as svg_input, open(nameSav, 'wb') as png_output: # svg转换png #canvasvg.svg2png(bytestring=svg_input.read(), write_to=png_output) shutil.rmtree(tmpdir) # 清除临时文件夹 t.exitonclick()
def viz_mountain(self, sstr, seq): """ Returns svg of secondary structure mountain plot """ # Create a Tk instance master = Tk() master.title("Mountain Plot") master.resizable(width = 0, height = 0) # Create canvas canvaswidth = 800 canvasheight = 600 w = Canvas(master, width = canvaswidth, height = canvasheight) w.pack() w.configure(background = "white") enclosures = [] max_enclosures = 0 for i in seq: enclosures.append({"base": i, "enclosures": 0}) for b1, b2 in sstr: for j in enclosures[(b1 + 1):b2]: j["enclosures"] += 1 if max_enclosures < j["enclosures"]: max_enclosures += 1 # Define bounding box of plot and other plot variables plot_x1 = 100 plot_x2 = canvaswidth - 150 plot_y1 = 50 plot_y2 = canvasheight - 50 xinc = (plot_x2 - plot_x1) / len(seq) yinc = (plot_y2 - plot_y1) / (max_enclosures if max_enclosures else 1) # Draw axes and labels w.create_line(plot_x1, plot_y1, plot_x1, plot_y2) w.create_line(plot_x1, plot_y2, plot_x2, plot_y2) w.create_text((plot_x2 - plot_x1) / 2 + plot_x1, plot_y2 + 30, text = "Sequence Position") w.create_text(plot_x1, plot_y1 - 15, text = "Enclosing Base Pairs") # Draw tick marks for i in range(10): w.create_line # Draw legend if 'U' in seq: colors = {'G': "green", 'C': "blue", 'A': "red", 'U': "yellow"} else: colors = {'G': "green", 'C': "blue", 'A': "red", 'T': "yellow"} legendx = plot_x2 + 20 legendy = plot_y1 + 70 w.create_rectangle(legendx - 20, legendy - 20, legendx + 50, legendy + 100) w.create_text(legendx - 10, legendy - 10, anchor = NW, text="LEGEND:") for index, (key, value) in enumerate(colors.iteritems()): w.create_oval(legendx - 2, legendy + 20 + 20*index, legendx + 2, legendy + 24 + 20*index, outline = value, fill = value) w.create_text(legendx + 20, legendy + 22 + 20*index, text=key) # Draw bases points = [] for index, entry in enumerate(enclosures): base, height = entry["base"], entry["enclosures"] xcoord = index * xinc + plot_x1 ycoord = plot_y2 - height * yinc points.append({"x": xcoord, "y": ycoord}) w.create_oval(xcoord - 4, ycoord - 4, xcoord + 4, ycoord + 4, outline = colors[base], fill = colors[base]) # Connect the dots for index, point in enumerate(points[1:]): w.create_line(point["x"], point["y"], points[index]["x"], points[index]["y"], fill = "black") # Output to svg canvasvg.saveall("mountainplot.svg", w)
if len(args) == 3: try: import canvasvg except ImportError as e: print('Unable to import canvasvg: %s' % e, file=sys.stderr) else: save_diagram = args[2] args.pop() if len(args) < 2: print('Calling with default triangle size') height = 50 width= 100 else: try: args = [int(x) for x in args] height, width = args except ValueError as e: print('Unable to handle these dimensions', file=sys.stderr) print('Calling with default triangle size') screen = draw_diagram(height, width) if save_diagram: try: canvasvg.saveall(save_diagram, screen.getcanvas()) except EnvironmentError, e: print('Unable to save diagram in file %s: %s' % (save_diagram, e), file=sys.stderr) turtle.mainloop()