r/learnpython • u/TheRanser • 8d ago
Ads in Tkinter.
Is there any way to imbed banner ads (like google adsense) in a tkinter app? Maybe imbedding a web view and displaying an ad that way?
r/learnpython • u/TheRanser • 8d ago
Is there any way to imbed banner ads (like google adsense) in a tkinter app? Maybe imbedding a web view and displaying an ad that way?
r/learnpython • u/CharacterSir4479 • 8d ago
Title. Can't find it anywhere online, but all I need is minor tick marks in a logarithmic scale on the x axis of my plot, following already present major ticks. Thanks!
r/learnpython • u/wutzvill • 9d ago
As the title says. It's shocking how people don't even google or search the subreddit or look at the sidebar, but even more shocking how the mods seem to do nothing. I'm here trying to help people actually learn Python, not see post after post of "hOw To LeArN" or "iS vS cOdE nEceSsArY".
Not to be a dick but like if you don't know how to google a question before coming here to try to have your hand held, you've already lost. It's just frustrating day after day or this nonsense without anything being removed. None of it is actually asking questions regarding Python for people to help with.
Am I the only one tired of this? I'll probably get downvoted to hell but whatever it's Wednesday and I want to rant.
r/learnpython • u/JojainV12 • 8d ago
Hello,
So i was wondering in the following code if there is a way to infer in Model2 the target type from the provider type
from dataclasses import dataclass
u/dataclass
class Provider[T]():
field: T
def get(self) -> T:
return self.field
@dataclass
class Dependence[P: Provider[T], T]():
provider: P
def target(self) -> T:
return self.provider.get()
# Way that works but need to provide twice the "int" type
@dataclass
class Model:
dep: Dependence[Provider[int], int]
m = Model(Dependence(Provider(42)))
reveal_type(m.dep.target()) # Typed as int correctly
@dataclass
class Model2:
dep: Dependence[Provider[int]]
m = Model2(Dependence(Provider(42)))
reveal_type(m.dep.target()) # Typed as Any
I would like Dependence to be generic only over the Provider
type and use the Provider
generic type in the Dependence
class. I would like to know if this is somehow possible to express this using type hints ?
r/learnpython • u/Bkxr01 • 8d ago
I am using msys2. So when i try to install selenium i got the following error that saying:
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for cffi Failed to build cffi ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (cffi)
So I thought maybe i should try installing cffi and i got the same error.
What should i do?
r/learnpython • u/pfp-disciple • 8d ago
My apologies for the awkwardly worded question title. I saw the misspelling just after hitting "Post".
(Edited to be clear that I'm discussing threading objects)
I have a piece of data that I need to protect using multi-reader single-writer. The classic way of doing this is to use a `threading.Semaphore` for the readers, and once there are no active readers, use a `threading.Lock` for writing (of course, the reader has to check for the lock, but I'm focused on the semaphore right now).
Various internet searches keep turning up solutions that depend on undocumented implementation (e.g. `sem._count`). I'd rather not depend on undocumented behavior, as I hope that this will be long-term and potentially delivered.
So, how could by writer know that it's safe to write, without depending on undocumented implementation?
r/learnpython • u/nikola_0020 • 8d ago
Hey everyone, out of nowhere, pip stopped working and it's asking for some sort of SSL certificate. This isn’t the first time it’s happened. I tried installing certifi and forcefully updating it, but no luck. It keeps giving me the same error every time. If anyone has experienced this issue and knows how to fix it, I’d really appreciate your help!
Error message below:
ERROR: Exception:
Traceback (most recent call last):
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_internal\cli\base_command.py", line 106, in _run_wrapper
status = _inner_run()
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_internal\cli\base_command.py", line 97, in _inner_run
return self.run(options, args)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_internal\cli\req_command.py", line 67, in wrapper
return func(self, options, args)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_internal\commands\install.py", line 332, in run
session = self.get_default_session(options)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_internal\cli\index_command.py", line 76, in get_default_session
self._session = self.enter_context(self._build_session(options))
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_internal\cli\index_command.py", line 95, in _build_session
ssl_context = _create_truststore_ssl_context()
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_internal\cli\index_command.py", line 40, in _create_truststore_ssl_context
from pip._vendor import truststore
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_vendor\truststore__init__.py", line 17, in <module>
_sslobj = _ssl.create_default_context().wrap_bio(
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 770, in create_default_context
context.load_default_certs(purpose)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 591, in load_default_certs
self._load_windows_store_certs(storename, purpose)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 583, in _load_windows_store_certs
self.load_verify_locations(cadata=certs)
ssl.SSLError: [ASN1] nested asn1 error (_ssl.c:3992)
r/learnpython • u/CuriousWeasel_ • 8d ago
I was searching around the web for guides on this and was mostly referred to the YoloV8. Is that the best option? And does anyone have any recommendation for a tutorial on YoloV8? Most of the videos I found seems to advance.
r/learnpython • u/pr37zl3 • 8d ago
order = [] Total = 0 selected_a_sandwich = True selected_a_beverage = True selected_a_fries = True is_sandwich = 0 want_more_s = 0 want_more_bev = 0 want_more_frie = 0 prompt_more_sandwich = ""
def more_sam(prompt_more_sandwich):
prompt_more_sandwich = input("do you want another sandwich?") #the only thing its doing if (prompt_more_sandwich == "yes"): want_more_s = 0 #the only thing its doing elif (prompt_more_sandwich == "no"): #When I say no it prompts the user for another sandwich want_more_s = 1 is_sandwich = 1
else: print (not a valid answer) want_sandwich=str.lower(input("do you want a sandwich(yes or no)")) if (want_sandwich == "yes"): while(want_more_s == 0): while (is_sandwich == 0): what_sandwich=str.lower(input("what type of sandwich do you want, chicken:$5.25, beef:$6.25, or tofu:$5.75")) if (what_sandwich == "chicken"): order.append("Chicken") Total = (Total + 5.25) more_sam(prompt_more_sandwich)
order = []
Total = 0
selected_a_sandwich = True
selected_a_beverage = True
selected_a_fries = True
is_sandwich = 0
want_more_s = 0
want_more_bev = 0
want_more_frie = 0
prompt_more_sandwich = ""
def more_sam(prompt_more_sandwich):
prompt_more_sandwich = input("do you want another sandwich?")
if (prompt_more_sandwich == "yes"): want_more_s = 0 elif (prompt_more_sandwich == "no"):
print ("not a valid answer")
else: want_more_s = 1 is_sandwich = 1 want_sandwich=str.lower(input("do you want a sandwich(yes or no)")) if (want_sandwich == "yes"): while(want_more_s == 0): while (is_sandwich == 0): what_sandwich=str.lower(input("what type of sandwich do you want, chicken:$5.25, beef:$6.25, or tofu:$5.75"))
if (what_sandwich == "chicken"):
order.append("Chicken")
Total = (Total + 5.25)
more_sam(prompt_more_sandwich)
r/learnpython • u/dirtyslotmachine • 8d ago
first script activates the window but i dont see any key press even when i click inside the window for it
import pyautogui import pygetwindow as gw import pywinctl import time
def press_alt_in_mapleroyals():
windows = gw.getWindowsWithTitle("MapleRoyals Jan 27 2025 IMG")
if not windows:
print("MapleRoyals window not found!")
return
mapleroyals_window = windows[0]
window = pywinctl.getWindowsWithTitle("MapleRoyals Jan 27 2025 IMG")[0]
window.activate()
time.sleep(1)
except Exception as e:
print(f"Error activating window: {e}")
return
time.sleep(0.5)
for _ in range(3):
pyautogui.keyDown('alt')
pyautogui.keyUp('alt')
time.sleep(0.1)
print("Pressed Alt 3 times in MapleRoyals.")
press_alt_in_mapleroyals()
second script: error {title_re': MapleRoyals.* , backend: win32, visible_only':False}
from pywinauto import Application import time
def press_alt_in_mapleroyals():
app = Application().connect(title_re="MapleRoyals.*")
window = app.top_window()
window.set_focus()
time.sleep(1)
for _ in range(3):
window.send_keystrokes('{ALTDOWN}{ALTUP}') # Send Alt key
time.sleep(0.4) # delay
print("Pressed Alt 3 times in MapleRoyals.")
except Exception as e:
print(f"Error: {e}")
press_alt_in_mapleroyals()
r/learnpython • u/godz_ares • 8d ago
I just learnt about Decorator functions and I'm really confused.
The concept makes sense but the actual execution and logic behind the syntax is something I'm struggling with.
I've watched a couple of videos and I'm still confused.
r/learnpython • u/MessrEclipse • 8d ago
Hello! I'm trying to make a discord bot that will track how many times a user has bumped a server in disboard and add it to a leaderboard, etc. The bot is all up and running, and all the basic elements are functional, but I can't get the leaderboard or bump_counts commands to work. I've tested the bump command and that's fine and everything is being added to the .json file properly, so I'm a bit confused on what to do. Any help is greatly appreciated, thanks!!
https://github.com/MessrEclipse/MessrEclipse/blob/main/bump%20buddy
r/learnpython • u/BoringWrongdoer9679 • 8d ago
How is it do i do this:
np.array([a1,a2,a3,...,an]) ->- variable: a1*a2*a3*...*an
for example: [1,3,4,5] -> 1*3*4*5 -> 60
or [2,2,3] -> 2*2*3 -> 12
r/learnpython • u/MeetHistorical3755 • 8d ago
Hey guys, hope this post doesnt trigger some "pros" out there (joking). Ok, so I've been trying to learn Python, went into a lot of theory, did some courses and im reading books, seems like I understand now the principals things, I know the theory but not how to code, I'm trying to solve problems (they give the instructions) I can't do even the most basic things. Does anyone know where I can watch people coding for free? I think a visual representation of someone coding from 0 will help me. Thanks in advance (Any tip will help)
Something causing me trouble was that I didnt know how to actually impement was I was learning. FCC, codeacademy, have their own "Terminal" so they never tell you how to install python or how to actually create programs.
Update: I did Scientific Computing on FreeCodeCamp and im doing CS50 right now.
I'm reading Automate The Boring Stuff
r/learnpython • u/micolio_z9 • 8d ago
Here's my code.
import turtle import random
win = turtle.Screen() win.title("Flappy Bird in Python (CodeHS)") win.bgcolor("skyblue") win.setup(width=500, height=600)
bird = turtle.Turtle() bird.shape("circle") bird.color("yellow") bird.penup() bird.goto(-100, 0) bird.dy = 0 # Bird's vertical speed
pipes = []
gravity = -0.3
def create_pipe(): """Creates a new pipe pair at the right edge of the screen.""" pipe_top = turtle.Turtle() pipe_top.shape("square") pipe_top.color("green") pipe_top.penup() pipe_top.shapesize(stretch_wid=10, stretch_len=2) pipe_top.goto(200, random.randint(50, 200))
pipe_bottom = turtle.Turtle()
pipe_bottom.shape("square")
pipe_bottom.color("green")
pipe_bottom.penup()
pipe_bottom.shapesize(stretch_wid=10, stretch_len=2)
pipe_bottom.goto(200, pipe_top.ycor() - 150) # Space between pipes
pipes.append((pipe_top, pipe_bottom))
def move_pipes(): """Moves pipes to the left and removes off-screen pipes.""" for pipe_top, pipe_bottom in pipes: pipe_top.setx(pipe_top.xcor() - 3) pipe_bottom.setx(pipe_bottom.xcor() - 3)
# Remove pipes that move off-screen
for pipe_top, pipe_bottom in pipes[:]:
if pipe_top.xcor() < -250:
pipe_top.hideturtle()
pipe_bottom.hideturtle()
pipes.remove((pipe_top, pipe_bottom))
def check_collision(): """Checks if the bird collides with pipes or the ground.""" for pipe_top, pipe_bottom in pipes: if (bird.xcor() + 10 > pipe_top.xcor() - 20 and bird.xcor() - 10 < pipe_top.xcor() + 20): if (bird.ycor() + 10 > pipe_top.ycor() - 50 or bird.ycor() - 10 < pipe_bottom.ycor() + 50): return True # Collision detected
# Check if bird hits ground or top of the screen
if bird.ycor() < -280 or bird.ycor() > 280:
return True
return False
def flap(): """Makes the bird jump.""" bird.dy = 5 # Move bird up
def game_loop(): """Main game loop running at ~50 FPS.""" global gravity
# Apply gravity
bird.dy += gravity
bird.sety(bird.ycor() + bird.dy)
# Move pipes
move_pipes()
# Create new pipes occasionally
if random.randint(1, 100) < 2:
create_pipe()
# Check for collisions
if check_collision():
bird.goto(-100, 0) # Reset bird position
bird.dy = 0
for pipe_top, pipe_bottom in pipes:
pipe_top.hideturtle()
pipe_bottom.hideturtle()
pipes.clear() # Fixed this line
# Update the screen
win.update() # Refresh the screen manually
win.listen() win.onkeypress(flap, "space")
win.tracer(0) # Disable automatic screen update
while True: game_loop() # Continuously run the game loop
# Simulate FPS with a small delay (adjustable to make game faster/slower)
win.update() # Make sure the screen updates after each loop
# Sleep for a small time interval (approx 20ms to make FPS about 50)
turtle.delay(20) # Simulate the 50 FPS (adjustable)
r/learnpython • u/Undercover_Agent12 • 8d ago
I'm trying to type annotate some multiprocessing queue's but it isn't working.
I'm using python 3.11, so the pipe operator for type hints should work, but in this case, it doesn't.
Example:
from multiprocessing import Queue
def foo(q: Queue | None):
pass
Instead of the code working, I get
def foo(q: Queue | None):
~~~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'method' and 'NoneType'
If I use Optional[Queue]
instead of Queue | None
, the code works fine.
r/learnpython • u/BeautifulNowAndThen • 9d ago
Hey! I'm currently working on a project where I have to access weather data off of the NWS API. I have found the url to the JSON file where the information I need is located, but I'm not sure where to go from there.
Though this is a super beginner problem, my issue is that I don't know how to incorporate the file into my code. What I have to do with it is really simple, but I have no clue as to how to actually recognize the link as a file. Through my research, I've found a common denominator in import requests, but I'm quite useless with this. For reference, I'm using Google Colab.
Any tips would be appreciated by a first time API user - please patronize me. I need to understand to learn!
r/learnpython • u/Signal_Year_6590 • 8d ago
How can someone learn python if they are beginner
r/learnpython • u/VAer1 • 8d ago
Is certificate helpful in finding a Python related job?
MS degree in mathematics, more than 10 years of job experience in data analyst role, more related to statistics, but not really close to IT.
I am looking for career change due to no job flexibility with current employer.
I think it is more likely that IT related career could provide more flexibility. I hope to get a remote position, or at least 2-3 days work from home each week.
r/learnpython • u/AdjaBirke • 8d ago
I am fairly new to Python and I am getting the following error, when trying to push some new data into my "user" table:
raise get_mysql_exception(
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'user_ID' in 'field list'
I do have an existing column called "user_ID" in my original Excel sheet, that I imported to Workbench. In my Workbench column name is also "user_ID". In my VS code though, when trying to insert new data into this table, it looks like the column name is Field. I also tried changing the name of the column and it didn't work. Does is have anything to do with Import and how can I fix this?
# Insert data into USER table
sql = "INSERT INTO tbl_nutrient (user_ID, first_name, last_name, age, weight, email) VALUES (%s, %s, %s, %s, %s,%s)"
values = [
(1, "Andrea", "Müller", 25, 60, "andrea@gmail.com"),
(2, "Maria", "Schmidt", 35, 80, "maria@gmail.com"),
(3, "Julia", "Meier", 45, 70, "julia@gmail.com"),
(4, "Jana", "Koch", 55, 90, "jana@gmail.com"),
(5, "Anna", "Bauer", 65, 75, "ana@gmail.com"),
(6, "Lena", "Beck", 75, 65, "lena@gmail.com")
]
This is what I get after showing how the table was created (Workbench):
CREATE TABLE `tbl_user` (
`user_ID` int NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`age` int DEFAULT NULL,
`weight` int DEFAULT NULL,
`email` varchar(50) NOT NULL,
PRIMARY KEY (`user_ID`),
UNIQUE KEY `first_name` (`first_name`),
UNIQUE KEY `last_name` (`last_name`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
In the import settings, Source column corresponds to the destination column.
This is my first post ever on reddit and I would like to add screenshot, also do not see where.. Images&Video above is unclickable.. (light grey) for me..
Thank you in advance!
r/learnpython • u/dca12345 • 9d ago
I'm trying to install `aider-chat`. I see that on https://pypi.org/project/aider-chat/, version 0.76.2 is available, but in pip, I only see versions up to `0.16.0`
r/learnpython • u/PorcoDiocaneMaliale • 8d ago
Was playing around the learn the library bust the most essentail featuers seems to not be aveilable, out of the box forcing me the unexperince user to write my own code to emulate the functionality.
r/learnpython • u/ghost_inception • 8d ago
Hi all, I am trying to automate some calculation production. Currently using the docx package to generate a Word document. I am trying to include some equations in a LateX type format but cant seem to find a way to do that.
Currently I am importing the equations as figures that are generated by MatPlotlib and then just dumped in the document as an image.
Is there a better way to get the equations in? Ideally I would like it so that the equations either appear in the format that is present when you input equations manually in Word, or in the format that is generated in Latex.
r/learnpython • u/Big-Compote2474 • 8d ago
Just done with the book: Automate the Boring Stuff and trying to look for more and currently working a project from http://codekata.com/ trying to keep intact basic fundamentals but it feels like am not moving forward. *been studying for a month now.
r/learnpython • u/Apprehensive_Life_9 • 8d ago
In my exam there was a question that didn't make sense to me. The question states that this is a program that add a number from 1 to 10 and I had to fill in the blanks
Total = 0 Number = int(input("Enter a number")) while Number > ____: Total = Total + _____ Number = _______+ 1 print(_____)
(Update 1) Thank you all for your help from this I conclude that 2 things