r/pythonhelp • • Mar 17 '22

Trying to output images in a grid

2 Upvotes

Hi all, I'm trying to output some images from an array of file paths to a grid with tkinter and PIL.

The code recreates the same label box repositions it and changes the image on each loop. How do i create a new label each loop?

EDIT: IF anyone has a more elegant solution, please let me know!

#files is a array of local image address i.e d:\photos\dirname\photoname.jpg
for file in files:       
        image_data = file
        loaded_img = Image.open(image_data)
        resized_img = loaded_img.resize(TARGET_SIZE)
        photo_img = ImageTk.PhotoImage(resized_img)
        make_label(root, x, y, 200, 166, photo_img)    
        x=x+200
        if(x > 1000):
            y = y + 166
            x = 0
        if(y > 320):
            break

r/pythonhelp • • Mar 16 '22

python game project not working, any ideas to fix it? (code and stuff is all in description)

2 Upvotes

So I was following a tutorial on making a pong game using the turtle library in python in order to practice my python skills I recently learned. However, my code doesn't make the program work properly, I listed the issues and code below, please help if you can!

First, when the terminal opens, the window doesn't have an exit button or anything, which makes weird as someone playing the game I imagine.

The second issue is that the paddles move incorrectly, when I press the "q" and "v" keys, which are supposed to move the second paddle (the paddle on the right side, they move the paddle on the left side. even though my functions declared it to be the second paddle.

The third issue is also related to the paddles, both of the paddles in the pong game don't move properly when I press the proper up and down keys in the game.

I was following a tutorial on youtube from freecodecamp, so Im not sure why it isnt working

If you know how to solve this, I attached the code below, any help is appreciated.

Edit: some were saying to fix the code, so i made a copy on pastebin

pastebin link: https://pastebin.com/yd0t8vvE

import turtle

wn = turtle.Screen()

wn.title=("Pong game")

wn.bgcolor("black")

wn.setup(width=800, height=500)

wn.tracer(0)

#The first paddle (Paddle A)

paddle_a = turtle.Turtle()

paddle_a.speed(0)

paddle_a.shape("square")

paddle_a.shapesize(stretch_wid=5, stretch_len=1)

paddle_a.color("green")

paddle_a.penup()

paddle_a.goto(-350, 0)

#Paddle B (The second Paddle)

paddle_b = turtle.Turtle()

paddle_b.speed(0)

paddle_b.shape("square")

paddle_b.shapesize(stretch_wid=5, stretch_len=1)

paddle_b.color("green")

paddle_b.penup()

paddle_b.goto(-350, 0)

#BALL

ball = turtle.Turtle()

ball.speed(0)

ball.shape("square")

ball.shapesize(stretch_wid=5, stretch_len=1)

ball.color("green")

ball.penup()

ball.goto(0, 0)

#Function

def paddle_a_up():

y = paddle_a.ycor()  y+= 20  paddle_a.sety(y) 

def paddle_a_down():

y = paddle_a.ycor()  y -= 20  paddle_a.sety(y) 

def paddle_b_up():

y = paddle_b.ycor()  y += 20  paddle_b.sety(y) 

def paddle_b_down():

y = paddle_b.ycor()  y -= 20  paddle_b.sety(y) 

#Keyboard finding

wn.listen()

wn.onkeypress(paddle_a_up, "w")

wn.onkeypress(paddle_a_down, "s")

wn.onkeypress(paddle_b_up, "q")

wn.onkeypress(paddle_b_down, "v")

#MAIN LOOP

while True:

wn.update()

r/pythonhelp • • Mar 11 '22

SOLVED Problem with variables in for loop not working outside of the loop

2 Upvotes

I'm self taught on Python, and this exact issue has had me stumped for 2 days now. Normally enough googling fixes it, but I cannot get this fixed, and it's driving me crazy. It's got to be something simple, but what???

I have a seperate python app that creates a CSV from a restAPI. I then use the following code to be able to search (and eventually do equations) within the CSV that was downloaded. This is just the beginning of the project, I'm just trying to get data from the CSV file to populate in one of the tkinter Entry boxes for now, but I get errors saying "NameError: name 'ha' is not defined". Except it is defined (I thought), and to my knowledge, the scope of a variable created within the for loop is not a local variable, and should therefore fall under "Class MyWindow:", right?

Also, I know I should be using "while open" statements for the 2 CSV files, but I was concerned that was causing a problem so I changed it for now.

import string
from tkinter import *
import csv
from operator import eq
import os

class MyWindow:
    def __init__(self, win):
        self.lbl1=Label(win, text='Item Name')
        self.lbl1.place(x=150, y=20)
        self.lblname=Label(win, text='Name')
        self.lblname.place(x=50, y=100)
        self.lblha=Label(win, text='High Alch')
        self.lblha.place(x=50, y=120)
        self.lbl3=Label(win, text='Result')
        self.lbl3.place(x=100, y=200)
        self.t1=Entry(bd=3)
        self.t1.place(x=150, y=50)
        self.tname=Entry()
        self.tname.place(x=100, y=100)
        self.tha=Entry()
        self.tha.place(x=100, y=120)
        self.t3=Entry()
        self.t3.place(x=200, y=200)
        self.b1=Button(win, text='Submit', command=self.search)
        self.b1.place(x=280, y=50)

    def search(self):
        file = open('1h.csv', 'r')
        rsfile = open('mapping.csv', 'r')
        reader = csv.reader(file)
        rsmap = csv.reader(rsfile)
        self.tname.delete(0, 'end')
        self.tha.delete(0, 'end')
        self.t3.delete(0, 'end')

        for row in rsmap:
            if self.t1 == row[8]:
                self.tname = row[8]
                self.ha = row[6] #THIS IS THE DECLARATION IM REFERRING TO
                self.limit = row[4]
                self.itemid = row[1]
                self.t3.insert(END, str(self.name))
        for row in reader:
            if '561' == row[0]:
                self.naturecost = row[3]
                self.Naturecost = float(self.naturecost)
            if self.t1 == row[0]:
                self.hourlow = row[3]
                self.Hourlow = float(hourlow)
                self.hourvol = row[4]
                self.t1=row[0]

        iname=self.t1.get()
        self.tname.insert(END, str(self.ha)) #DOES NOT WORK
        self.t3.insert(END, str(iname)) #DOES WORK
        file.close()
        rsfile.close()

window=Tk()
mywin=MyWindow(window)
window.title('Hello Python')
window.geometry("400x300+10+10")
window.mainloop()

r/pythonhelp • • Mar 09 '22

How do I call a string and int in the same line?

2 Upvotes

I have the most simple project ever, and literally everything about it works until I try to call the number and say "it's even" in the same line.

Is there another way to do this?

theList = list(range(1, 11))

evenText = " is even"

for num in theList: if num % 2 == 0: print(num + " is even")
else: print (num + " is odd")


r/pythonhelp • • Feb 19 '22

pip3 install -r requirements.txt not working

2 Upvotes

Hello,

I have never dealt with Python before so this could be just a simple problem: I'm trying to run this Python code and step 2 is to install libaries with "pip3 install -r requirements.txt", but every time I type this in my console I get no feedback, whats the problem? I think I'm doing something wrong with installing the libraries because when I type "instalooter login" in step 3 I get an error message "zsh: command not found: instalooter".

Terminal: https://drive.google.com/file/d/1YjY4bmPaqOXjuCsHQ8NLHbyceTTjmIXC/view?usp=sharing

Python code: https://github.com/nathan-149/automated_youtube_channel


r/pythonhelp • • Feb 09 '22

How to convert csv to xlsx with openpyxl?

2 Upvotes

Hello everyone! I'am creating a code for convert csv to xlsx but my code has a problem, it can convert the values only to A1 collumn. How to make code to be can writing values from csv to any selected collumn?

My Code:

import csv

import openpyxl

wb = openpyxl.Workbook()

ws = wb.active

with open('text.csv') as f:

reader = csv.reader(f, delimiter=':')

for row in reader:

ws.append(row)

wb.save('file.xlsx')


r/pythonhelp • • Jan 15 '22

how do i do this?

2 Upvotes

when you run the command 'os.system("gnome-terminal -e 'sudo apt-get update'") is there any way to add more commands into the same terminal? thanks!


r/pythonhelp • • Dec 23 '21

Updating a Dataframe from another Dataframe

2 Upvotes

Hi All,

I hope you are well

I was wondering if I could get some help!

I have 2 dataframes, e.g.:

Unique ID Email Number

0 123 No No

1 456 No No

2 789 No No

2)

Unique ID Email2 Number2

0 123 Yes Yes

1 456 Yes Yes

2 789 Yes No

How can I update the 1st dataframe so it has the values of the second data frame based on Unique ID, therefore the 1st dataframe becomes:

Unique ID Email Number

0 123 Yes Yes

1 456 Yes Yes

2 789 Yes No

Apologies if this does not make sense!


r/pythonhelp • • Dec 04 '21

HOMEWORK inquiries about python

2 Upvotes

Hello, this is my first post on this subreddit. I just wanted to know how to append items to a list which correspond to each other. For example I have 3 people input their names and the amount of property they sold, how do I add it to the list in a way that they get stored individually under the same index.


r/pythonhelp • • Dec 01 '21

How to sort whole strings alphabetically?

2 Upvotes

So I was wondering if I have strings like this:

“hi my name is Sara” “Hello dog” “hi name”

Then how would I get an output where it looks like:

“Hello dog”(since it has a H and is capital letter) “hi my name is Sara” “hi name” (since n comes after m)

I can’t seem to figure this out as the sort() function cannot work with this as I don’t want it to sort individually but as strings.


r/pythonhelp • • Oct 07 '21

HOMEWORK Easy: just started learning python. Can’t figure out how to assign the result to a variable. Don’t know what I did wrong here. Thank you to anyone willing to explain.

Post image
2 Upvotes

r/pythonhelp • • Oct 06 '21

Problem nested loop in a personal challenge project (my code).

2 Upvotes

I am having a problem with my nested loop in this code I am playing with. This is not for class, but a personal quest. The goal is to random generate sets of 8 bits based on how many characters (ASCII) they want and then save to file output to "random.txt". The problem area begins with the "else:" statement and ends before "finally:", The problem is that it executes 8 iterations of the inner loop and once of the outer loop so I always get 8 bits.

Example of desired output of random.txt:

01001000 01100101 01101100 01101100 01101111 00100000 01010010 01100101 01100100 01100100 01101001 01110100 00100001

Current code:

import random

def generate():
    random_num = random.randint(0,1)
    return random_num

def main():
    try:
        output = open("random.txt", "w")

        num_of_num = int(input("How many characters should the file hold?"))

    except Exception as PotentialError:
           print("An error has occured.", PotentialError)

    else:
        for num_count in range(0, num_of_num + 1):
            for bits in range (1, 7 + 1):
                random_num = generate()
                output.write(str(random_num))
            return bits
        return num_count

        print(num_of_num, "numbers have been written to the file random.txt")

    finally:
            output.close()
main()

r/pythonhelp • • Oct 02 '21

I'm getting this error, wb+ or ab/ab+ won't work with Google Collab. The file keeps coming up empty. This exact cell was working a few months back

Post image
2 Upvotes

r/pythonhelp • • Sep 24 '21

I cannot understand this basic code

2 Upvotes

i=0

while i < 6:

i += 1

if i == 3 :

continue

print(i)

I know the answer is 6, but how?

It says it is adding the i value by 1.

Also, why is the third line important

Please help. I am trying to study for my exam


r/pythonhelp • • Sep 19 '21

HOMEWORK The contents of your standard output is incorrect?

2 Upvotes

I am working on a chapter project on Pearson Revel.

The question is:

At one college, the tuition for a full-time student is $8,000 per semester. It has been announced that the tuition will increase by 3 percent each year for the next 5 years. Write a program with a loop that displays the projected semester tuition amount for the next 5 years.The program should print out the result in the form

In 1 year, the tuition will be $8002.3.
In 2 years, the tuition will be $8103.2.
In 3 years, …
In 4 years, …
In 5 years, …

(If, for example, the tuition would cost 8002.3 dollars in one year, etc.)Look carefully at the following sample run of the program. In particular, notice the wording of the messages and the placement of spaces and punctuation. Your program's output must match this.Sample Run

In 1 year, the tuition will be $8240.0.
In 2 years, the tuition will be $8487.2.
In 3 years, the tuition will be $8741.816.
In 4 years, the tuition will be $9004.07048.
In 5 years, the tuition will be $9274.192594400001.

So far, I have input this code: (normal indentation is followed, just wasn't applied when copy/paste)

year = 1

tuition = 8000

while year <= 5:

if year == 1:

tuition = 1.03 * tuition

print( " In ", year, " year, the tuition will be $", + tuition,".", sep="" )

year = year + 1

else:

tuition = 1.03 * tuition

print( " In ", year, " years, the tuition will be $", + tuition,".", sep="" )

year = year + 1

The problem I am running into is that the output with my code matches the output with the correct code on the Test Case Table, but I am still getting a _stdout argument. The only real pointer the website is giving is that "The contents of your standard output is incorrect." even though my output literally matches character for character of the correct answer. Anyone know what I should do?

My Output:

In 1 year, the tuition will be $8240.0. In 2 years, the tuition will be $8487.2. In 3 years, the tuition will be $8741.816. In 4 years, the tuition will be $9004.07048. In 5 years, the tuition will be $9274.192594400001.

Correct Output:

In 1 year, the tuition will be $8240.0. In 2 years, the tuition will be $8487.2. In 3 years, the tuition will be $8741.816. In 4 years, the tuition will be $9004.07048. In 5 years, the tuition will be $9274.192594400001.


r/pythonhelp • • Sep 18 '21

Help needed with Cave Game

2 Upvotes

Hey y'all, so I'm trying to create a cave game where it prompts the user for their character name, and gives them a choice of going through three caves; and based on what they pick, they get a random outcome. I keep getting an error when I'm trying to insert a variable to print out a name in a statement, and am just curious if my code even makes sense, would any of you be able to help out?

import random

import time

def displayIntro():

print('You are in a land full of dragons. In front of you,')

print('you see two caves. In one cave, the dragon is friendly')

print('and will share his treasure with you. The other dragon')

print('is greedy and hungry, and will eat you on sight.')

print()

def askname():

print("What would you like to call your character?")

n=input()

def chooseCave():

cave = ''

while cave!= '1' and cave!= '2' and cave!= "3":

print("Which cave should",n,"go into? (1, 2, or 3)")

cave = input()

return cave

def checkCave(chosenCave):

print(n,"approaches the cave...")

time.sleep(2)

print('It is dark and spooky...')

time.sleep(2)

print("A large dragon jumps out in front of",n,"!He opens his jaws and...")

print()

time.sleep(2)

friendlyCave = random.randint(1, 3)

convoCave = random.randint(1,3)

if chosenCave == str(friendlyCave):

print('Gives you his treasure!')

if chosenCave == str(convoCave):

print('Starts talking to you!')

else:

print('Gobbles you down in one bite!')

playAgain = 'yes'

while playAgain == 'yes' or playAgain == 'y':

displayIntro()

caveNumber = chooseCave()

checkCave(caveNumber)

print('Do you want to play again? (yes or no)')

playAgain = input()

Thanks for any help, really appreciate it!


r/pythonhelp • • Sep 17 '21

Is there a way to run your code?

2 Upvotes

If you made a project on Python and you want to be able to run the code on another electric without installing Python what would be the best way of doing that? Duse it have to be a game or can it be just raw code that you can run?


r/pythonhelp • • Aug 16 '21

Pycocotools failed to build wheel

2 Upvotes

Hello everybody, I've recently begun to dip my feet into object detection and tensorflow. While it has proven challenging it feels quite enjoyable and I feel I've learnt a ton from it. Recently however Ive run into an issue I have yet to be able to solve.

I have been following this tutorial: Real Time Face Mask Detection with Tensorflow and Python | Custom Object Detection w/ MobileNet SSD - YouTube

When it gets to the part where we run the:

python Tensorflow/models/research/object_detection/model_main_tf2.py --model_dir=Tensorflow/workspace/models/my_ssd_mobnet --pipeline_config_path=Tensorflow/workspace/models/my_ssd_mobnet/pipeline.config --num_train_steps=5000

command, I am instead getting the error that there is no module named pycocotools. I attempted to solve this by running the appropriate pip install command but when I do it I get this error:

 ERROR: Command errored out with exit status 1:
   command: 'c:\program files (x86)\microsoft visual studio\shared\python37_64\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\moham\\AppData\\Local\\Temp\\pip-install-xfya3fgr\\pycocotools_b83c35bfc43b4320b51f4dfe9a656571\\setup.py'"'"'; __file__='"'"'C:\\Users\\moham\\AppData\\Local\\Temp\\pip-install-xfya3fgr\\pycocotools_b83c35bfc43b4320b51f4dfe9a656571\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\moham\AppData\Local\Temp\pip-wheel-8g0iskd2'
       cwd: C:\Users\moham\AppData\Local\Temp\pip-install-xfya3fgr\pycocotools_b83c35bfc43b4320b51f4dfe9a656571\
  Complete output (16 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.7
  creating build\lib.win-amd64-3.7\pycocotools
  copying pycocotools\coco.py -> build\lib.win-amd64-3.7\pycocotools
  copying pycocotools\cocoeval.py -> build\lib.win-amd64-3.7\pycocotools
  copying pycocotools\mask.py -> build\lib.win-amd64-3.7\pycocotools
  copying pycocotools__init__.py -> build\lib.win-amd64-3.7\pycocotools
  running build_ext
  cythoning pycocotools/_mask.pyx to pycocotools_mask.c
  C:\Users\moham\AppData\Roaming\Python\Python37\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: C:\Users\moham\AppData\Local\Temp\pip-install-xfya3fgr\pycocotools_b83c35bfc43b4320b51f4dfe9a656571\pycocotools_mask.pyx
    tree = Parsing.p_module(s, pxd, full_module_name)
  building 'pycocotools._mask' extension
  error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
  ----------------------------------------
  ERROR: Failed building wheel for pycocotools

I have happened upon some solutions online on github and such but I havent had much luck solving this. Any resources that may help me in understanding what this error is and how I can fix it is greatly appreciated. Thank you for your time and have a great day!


r/pythonhelp • • Aug 06 '21

HOMEWORK Having trouble categorising a number as a letter (check comments for context)

Post image
2 Upvotes

r/pythonhelp • • Jul 07 '21

Python Invoke tasks for Docker using Git Bash not working on a Windows system

2 Upvotes

Hello dear people of r/pythonhelp, I wish you a very good day. I'm currently trying to make some simple docker and docker-compose tasks with the help of Python's invoke library. One of my teammates only has access to a Windows laptop and has to inevitably work like this. I originally wrote and ran them on Linux without any issues but the commands do not work for him. Here's how my script looks like after trying to set up the Windows option:

from invoke import task
import os
if os.name == 'nt':
    SYSTEM_DOCKER_PREFIX = 'winpty docker exec -it'
    pty = False
else:
    pty = True
    SYSTEM_DOCKER_PREFIX = 'docker exec -it'

def manage(c, command, restart_docker=False):
    """Run django manage.py commands"""
    if restart_docker:
        up(c, True)
    container_name = get_full_container_name(c, 'webapp')
    c.run(f'{SYSTEM_DOCKER_PREFIX} {container_name} python3 manage.py {command}', pty=pty)

@task
def docker_exec(c, command):
    """Run arbitrary commands in the web app container"""
    container_name = get_full_container_name(c, 'webapp')
    c.run(f'{SYSTEM_DOCKER_PREFIX} {container_name} {command}', pty=pty)

These tasks (Though I have others more complex) would just be used to shorten some of the lengthy docker-compose commands to build my containers, a DJANGO app, and simple django stuff like createsuperuser, migrate, shell, etc. If I run one of these commands in Git Bash in Windows I always get this error:

$ inv task.manage createsuperuser
webapp_1
stdin is not a tty

$ inv task.manage shell
webapp_1
stdin is not a tty

Trying to research this problem, it seems there's some issues with pty=True and winpty. I already followed the suggestions of including winpty, changing pty to false, and still nothing. Furthermore, looking for this error online doesn't really pop up anything of help.

If anyone has ever faced a similar issue and could give some help, I'd be really grateful. Thank you guys and this community as always for helping so many people.


r/pythonhelp • • Jun 23 '21

How do I update an async function with a sync function?

2 Upvotes

I'm writing a discord music bot and have a problem with making a queue:

I think I slightly understand the error message I get:

RuntimeWarning: coroutine 'Command.__call__' was never awaited

I'm trying to call a sync function queueNext() from the async function play_combat() because queueNext() handles the queue lists of many functions in the same way.

  • Is it possible to mix sync and async functions?

  • How do you prevent sync functions to not be 'never awaited'?

  • how should I manipulate data from the async functions?

My code:

import discord
from discord.ext 
import commands 
import youtube_dl   
import os import random 
import numpy as np
client = commands.Bot(command_prefix='><')
defaultChannel='vc1' 
currentChannel='' 
musicFolder = r'C/path'
testlist=       ['no','testsong','war_horn','suspence']
queue = []

def queueNext(ctx, queue, listName): 
    queue.pop(0)    
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if not voice.is_playing():            
        if listName == 'testlist':
            play_combat(queue)       #here is the error

@client.command(aliases = ['combat'])
async def play_combat(ctx, vcName=currentChannel, queue=[]):
queue plays
    list=testlist
    listName='testlist'
a bool to check if another command was given
    for item in np.arange(len(testlist)): # make the queue as long as the list
        song = random.choice(list)
        queue.append(song)  #add a randomly selected song to end of queue
        list.remove(song)   #shortens the list and prevents duplications
    voiceChannel = discord.utils.get(ctx.guild.channels, name=str(vcName)) 
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if not voice.is_connected():      #check if I'm on the right vc
       await voiceChannel.connect()
    if not voice.is_playing(): # if no song is playing
        voice.play(discord.FFmpegPCMAudio(musicFolder+queue[0]+'.mp3'), after=lambda b: queueNext(ctx, queue, listName))


client.run('token')

r/pythonhelp • • Jun 12 '21

Using timg module for a generic image

2 Upvotes

Trying to get it so that an image in my code shows up during runtime along with the output. I put the following code in...

import timg

obj = timg.Renderer()
obj.load_image_from_file("arm.png")
obj.resize(76, 76)
obj.render(timg.ASCIIMethod)

And it makes an ASCII image. But I just want it to show the image as it is with no modification in style. Deleting the last line make the image not show up at all, leaving the parenthesis blank makes it not show up. Anyone know a solution involving modifying the code above to make it show the image just as it is unmodified in style?


r/pythonhelp • • Jun 08 '21

Can anybody help me with this script? In the output panel, it is supposed to send the coordinates of the 'k,' but it instead sends random numbers (Wherever I put the 'k'). However, for example, it is at (3, 3), but (0, 2) shows up in the output regardless of how many times I run it.

Post image
2 Upvotes

r/pythonhelp • • Jun 06 '21

'NoneType' object has no attribute 'find_all' with BeautifulSoup

2 Upvotes

The problem lies on line 15 and I'm not sure where to go from here.

import requests from bs4 import BeautifulSoup import pandas as pd

url = 'https://cryptoslam.io/topps-mlb/sales' requests.get(url) page = requests.get(url)

soup = BeautifulSoup(page.text, 'lxml')

table_data = soup.find('table', {'table table-striped table-bordered table-hover dataTables-example responsive dataTable no-footer dtr-inline collapsed'})

headers = []

for i in table_data.find_all('th'): title = i.text.strip() headers.append(title)

df = pd.DataFrame(columns = headers)

for j in table_data.find_all('tr'): row_data = j.find_all('td')

row = [tr.text.strip() for tr in row_data]

length = len(df) df.loc[length] = row

print(headers)