This is my main code:
import turtle
import random
from sys import exit
import canvasvg
import os
import tempfile
import shutil
import cairosvg
red = 125
green = 70
blue = 38
pen = 15
def runChk():
runAgain = input("Would you like to return to menu? Y/N (N will exit) \n")
if runAgain.upper() == "Y":
print("Running...")
turtle.clearscreen()
start()
elif runAgain.upper() == "N":
print("Exiting...")
exit()
else:
print("Invalid response.")
runChk()
def saveImg():
print("Done.")
save = input("Would you like to save this tree? Y/N \n")
if save.upper() == "Y":
filename = input("What would you like to name it? \n")
print("Ignore following warning...")
if not filename.lower().endswith('.png'):
filename += '.png'
target_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'Images', filename)
tmpdir = tempfile.mkdtemp() # create a temporary directory
tmpfile = os.path.join(tmpdir, 'tmp.svg') # name of file to save SVG to
ts = turtle.getscreen().getcanvas()
canvasvg.saveall(tmpfile, ts)
with open(tmpfile) as svg_input, open(target_path, 'wb') as png_output:
cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
shutil.rmtree(tmpdir) # clean up temp file(s)
print("Saved!")
runChk()
elif save.upper() == "N":
runChk()
else:
print("Invalid response. \n")
saveImg()
def tree(branchLen, red, green, blue, pen):
if branchLen > 3:
pen = pen*0.8
turtle.pensize(pen)
if (red > 10 and green < 140):
red = red - 15
green = green + 8
if branchLen > 5:
angle = random.randrange(18, 55)
angleTwo = 0.5*angle
sub = (0.8*(random.randrange(1,20)))
print("Angle 1: ", angle, "Angle 2: ", angleTwo, " Branch length subtracted by ", sub)
turtle.color(red, green, blue)
turtle.forward(branchLen)
turtle.right(angleTwo)
tree(branchLen-sub, red, green, blue, pen)
turtle.left(angle)
tree(branchLen-sub, red, green, blue, pen)
turtle.right(angleTwo)
turtle.backward(branchLen)
def main():
turtle.colormode(255)
turtle.bgcolor(102, 255, 255)
turtle.left(90)
turtle.up()
turtle.speed(0)
turtle.hideturtle()
turtle.backward(440)
turtle.down()
print("Please wait while I draw...")
tree(random.randrange(80, 95),red,green,blue, pen)
turtle.update()
saveImg()
def start():
live = 1
print("What would you like to do?\n")
usr = input("Type 'run' to start a fractal. \nType 'run static' to create a fractal without live drawing (faster). \nOr 'exit' to exit. \n")
if usr.upper() == "RUN":
live = 1
print("Running...")
main()
elif usr.upper() == "RUN STATIC":
live = 0
print("Running...")
turtle.tracer(0)
main()
elif usr.upper() == "EXIT":
print("Exiting...")
exit()
else:
print("Invalid response.")
start()
start()
it is called fractal.py. I copied that and canvasvg to the main python folder. I created a cx_freeze setup as so:
from cx_Freeze import setup, Executable
# NOTE: you can include any other necessary external imports here aswell
includefiles = [] # include any files here that you wish
includes = []
excludes = []
packages = ['turtle', 'random', 'sys', 'canvasvg', 'os', 'tempfile', 'shutil', 'cairosvg']
exe = Executable(
# what to build
script = "fractal.py", # the name of your main python script goes here
initScript = None,
base = None, # if creating a GUI instead of a console app, type "Win32GUI"
targetName = "Fractal Tree.exe", # this is the name of the executable file
copyDependentFiles = True,
compress = True,
appendScriptToExe = True,
appendScriptToLibrary = True,
icon = None # if you want to use an icon file, specify the file name here
)
setup(
# the actual setup & the definition of other misc. info
name = "Fractal Tree", # program name
version = "0.4.2",
description = 'Creates a fractal tree',
author = "TomSoft Programs",
options = {"build_exe": {"excludes":excludes,"packages":packages,
"include_files":includefiles}},
executables = [exe]
)
When I run cmd as python setup.py build, I get no errors. I go to the build folder and find my fractal.exe program. It closes very quickly and I can't get the full error (because of the speedy closing) but I know it says something like:
ReferenceError: 'module' object has no attribute '_fix_up_module'
What can I do to fix this? I'm very new to python and cx_freeze, so I'm sure I'm doing something wrong in setup.py.
For anyone who finds this, it's a bug with cx_freeze. You've done nothing wrong. Download cx_freeze from here, the bug is fixed at this download location.
Related
I am trying to improve a code I found online so that it doesn't waste so much paper.
The files I will be printing are small labels which do not take a lot of space. I would like to be able to "merge" those labels so that they'd be printed out by groups of 6 per page.
This is the code (it already has some modifications):
# Import libraries
import os
from pickle import TRUE
import time
import tkinter as tk
from tkinter import filedialog
def menu():
print("1- Retry")
print("0- Exit")
s=TRUE
while s:
opt = input("Select an option: ")
try:
if int(opt) == 1 or int(opt) == 0:
opt = int(opt)
s = False
except:
input("Press enter to try again.")
return opt
s = TRUE
while s:
root = tk.Tk()
root.withdraw()
path = filedialog.askdirectory()
try:
# Extracting all the contents in the directory corresponding to path
l_files = os.listdir(path)
# Iterating over all the files
for file in l_files:
# Instantiating the path of the file
file_path = f'{path}\\{file}'
# Checking whether the given file is a directory or not
if os.path.isfile(file_path):
try:
# Printing the file pertaining to file_path
os.startfile(file_path, 'print')
print(f'Printing {file}')
# Sleeping the program for 5 seconds so as to account the
# steady processing of the print operation.
time.sleep(5)
except:
# Catching if any error occurs and alerting the user
print(f'ALERT: {file} could not be printed! Please check\
the associated softwares, or the file type.')
else:
print(f'ALERT: {file} is not a file, so can not be printed!')
s = False
except:
print('No folder selected.')
opt = menu()
if opt == 0:
break
else:
pass
print('Task finished!')
I am trying to convert a text adventure originally made in vanilla Python to a Tkinter format. My attempt at this was to create a dictionary that would be updated whenever information was entered, but the dictionary information isn't saving and seems to revert back to an empty dict every time.
How would I do this ? Apologies if the question is unclear, I am very new to Tkinter and have been struggling with this for a long time.
Here is my code, all it needs to do is figure out if the player wants to activate the tutorial :
from tkinter import *
# Storage
game_text = {}
cmd = {}
root = Tk()
# Configuration
root.geometry ("1000x1000")
root.title("A New Dawn")
icon = PhotoImage(file = "C:/Users/gwynn/Desktop/wcnd_icon.png")
root.iconphoto(False, icon)
root.configure(bg="#006644")
# Parsers
def parse(tag, line):
game_text[tag] = Text(root, width = 200, height = 1)
game_text[tag].insert(INSERT, line)
game_text[tag].pack()
game_text[tag].tag_add(tag, '1.0', 'end')
game_text[tag].tag_config(tag, background = "#006644", foreground = "#8cd98c")
def cmd_parse(cmd_box):
cmd['cmd'] = cmd_box.widget.get()
cmd['cmd'] = cmd['cmd'].lower()
print(cmd['cmd'])
# The Game
parse('tutorial', "Welcome to WC : A New Dawn ! Before we begin - would you like to activate the tutorial ? [Y/N]")
cmd_box = Entry(root, background = '#096', foreground = "#b3e6b3", width = 200, border = 3)
cmd_box.pack()
cmd_box.bind("<Return>", cmd_parse)
print(cmd)
if 'cmd' in list(cmd):
if cmd['cmd'] == "y":
parse('tutorial_y', "Excellent ! The tutorial has been activated.")
elif cmd['cmd'] == "n":
parse('tutorial_n', "Excellent ! The tutorial has been deactivated.")
root.mainloop()
You are trying to manage cmd conditions before the user has even had the chance to type. You have to move your conditions (or call a function of your conditions) after you have actually retrieved the typed data.
def cmd_parse(event):
cmd = event.widget.get().lower()
if cmd == "y":
parse('tutorial_y', "Excellent ! The tutorial has been activated.")
elif cmd == "n":
parse('tutorial_n', "Excellent ! The tutorial has been deactivated.")
My program works fine but when it finished gives error like that :
could not convert to integer . Path ' exitCode'. value too big or too small for Int32
Python 3.7
from re import compile
from os import path, walk
from pywinauto import win32api
from easygui import fileopenbox
from pyautogui import confirm, alert
from sys import exit
def Find_Client_Path():
file_name = compile("LeagueClient.exe")
for driver in win32api.GetLogicalDriveStrings().split("\000")[:-1]:
for root, folders, files in walk(driver):
for file in files:
find_file = file_name.search(file)
if find_file:
return path.join(root, file)
return Find_Path_Manually()
def Find_Path_Manually():
alert(
"Please select LeagueClient.exe in Riot Games / League of Legends /.",
title="Warning",
button="Okay",
)
path = fileopenbox()
if path.find("LeagueClient.exe") != -1:
return path
else:
secim = confirm(
"You choose the worng file. Please select LeagueClient.exe in Riot Games / League of Legends / . If you want to close bot click EXIT button.",
title="UYARI!",
buttons=("OKAY", "EXIT"),
)
if secim == "EXIT":
sys.exit()
elif secim == "OKAY":
return Find_Path_Manually()
I am creating a small level designer in Python (using PyGame).
The program is supposed to just let you place down an image, change between images, export to a PNG file, and export image path and coordinates to where it was place in a text document. I have gotten all of these components to work, but I am stuck with one last component, and that is reading the text document back into PyGame, and re-placing all of the images in the correct places with the correct sprites.
The way that I have it currently (Which has been rewritten and Almost works) produces an error whenever I try to read from one of my exported files.
The error of course is:
stamped_surface.blit(image, (xcrds, ycrds))
TypeError: invalid destination position for blit
Here is my code:
import pygame as pg
import threading
import time
import pygame
from random import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfile
image_file = "../res/ExampleProject/TankGame/TankGameImg/tileGrass_transitionE.png"
f = open("../Saves/Backups/FailSafe.txt", "a+")
f.write("""
#################################################
# PyEngine #
# FailSafe #
# File #
# By MouseBatteries #
#################################################
""")
pg.init()
xcrds = 17
ycrds = 13
black = (0,0,0)
sw = 1280
sh = 720
screen = pg.display.set_mode((sw, sh))
pg.display.set_caption('thing')
image = pg.image.load(image_file).convert()
start_rect = image.get_rect()
image_rect = start_rect
running = True
stamped_surface = pg.Surface((sw, sh))
while running:
event = pg.event.poll()
keyinput = pg.key.get_pressed()
# Escape Program
if keyinput[pg.K_ESCAPE]:
fname = "../Saves/Design_complete.png"
pg.image.save(stamped_surface, fname)
print("File saved at {} ".format(fname))
quit()
#Save Work In Project File
if keyinput[pg.K_s]:
fname = "../Saves/LevelSave.png"
pg.image.save(stamped_surface, fname)
print("File saved at {} ".format(fname))
#Open New Selectable
if keyinput[pg.K_n]:
image_file = askopenfilename()
image = pg.image.load(image_file).convert()
print("Placable Updated!")
if keyinput[pg.K_e]:
fname = "../Saves/Export.png"
pg.image.save(stamped_surface, fname)
print("File saved at {} ".format(fname))
pg.quit()
#Recreate Terrain From File
if keyinput[pg.K_o]:
fileDest = askopenfilename()
openFile = open(fileDest, "r")
for line in openFile:
li = line.strip()
if li.startswith("Pec:"): #pec stands for "PyEngineCoords"
reimgpath = (line.rstrip())
nopecimgpath = reimgpath.replace("Pec:", "")
print(nopecimgpath)
image = pg.image.load(nopecimgpath).convert()
pg.display.update()
if li.startswith("Crdsx:"):
xposcrds = (line.rstrip())
xcrds = xposcrds.replace("Crdsx:", "")
x = int(xcrds)
print(x)
pg.display.update()
if li.startswith("Crdsy:"):
yposcrds = (line.rstrip())
ycrds = yposcrds.replace("Crdsy:", "")
y = int(ycrds)
print(y)
pg.display.update()
stamped_surface.blit(image, (xcrds, ycrds))
elif event.type == pg.QUIT:
running = False
elif event.type == pg.MOUSEMOTION:
image_rect = start_rect.move(event.pos)
elif event.type == pg.MOUSEBUTTONDOWN:
stamped_surface.blit(image, event.pos)
print("Image Placed!")
print(image_file, event.pos)
f.write("\nPec:" + image_file + "\nCrdsx:")
print(event.pos)
xpos_str = str(pg.mouse.get_pos()[0])
ypos_str = str(pg.mouse.get_pos()[1])
f.write(xpos_str)
f.write("\nCrdsy:")
f.write(ypos_str)
f.flush()
screen.fill(black)
screen.blit(stamped_surface, (0, 0))
screen.blit(image, image_rect)
pg.display.flip()
This program has a file system and certain controls to make things happen, so here they are:
ESC KEY - Auto Exports Program For Reference And Quits Program
S Key - Saves Surface as PNG file.
N Key - Prompts User to select new sprite to use
E Key - Exports Image To PNG with file prompt
O Key - Opens File With Coordinate data and image path data.
Image Of Root File System:
https://i.imgur.com/KouhmjK.png
A Few things you should know:
This program auto-saves every file position to the file that contains Coords and Image Paths.
The file system is relatively simple to work out by looking at the code, but if you need some assistance, please ask.
blits((source, dest, area), ...)) -> (Rect, ...) you are missing out the destination. Read here
And if you are making use of coordinates then use square brackets [x-co,y-co]
like this:
block.blit(image,[0,0])
This is my Program, Text Extraction from Image program:
import pytesseract
from PIL import Image
import os
from os.path import join
import sys
con_1 = True
store_1 = []
store_2 = []
store_3 = []
con_1 = True
print("Welcome to my Text Extraction from Image Program. Here you can extract text from any image.")
while con_1:
image_name = input("Enter your image's name:")
for root, dirs, files in os.walk("/home/"):
if image_name in files:
found = join(root, image_name)
store_1.append(found)
if len(store_1) == 0:
ask_1 = str(input("Your image was not found. Do you want to try again(Y/n)?:"))
if ask_1 == "Y" or ask_1 == "y":
con_1 = True
elif ask_1 == "N" or ask_1 == "n":
con_1 = False
else:
print("Your input is out of bounds. Please try again.")
else:
print("Your image was successfully found.")
image_open = Image.open(found)
image_text = pytesseract.image_to_string(image_open)
print(image_text)
break
This is the image I am testing it on:
And this is the most weirdest output I have ever seen:
‘Understanding how computer memory
ia tire terrae tec
programming lan
This is another image I am testing it on:
And another really weird output:
Sesh chee nia ec Hiok pc
RU hun oe
mete een
machines work while still being easy to learn.
I have never seen my program giving me such off-target and weird outputs. I have absolutely no idea how this is happening. I would very much like to know how to fix it as well as why my program is malfunctioning.