The main problem with your code is that you create a new PhotoImage for each pixel! Instead, create the PhotoImage once and just add the pixels in the double-for-loop.

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)

    picture = PhotoImage(width=(x2-x1), height=(y2-y1))
    for x in range(x1, x2):
        for y in range(y1, y2):
            r, g, b = photo.get(x, y)
            picture.put("#%02x%02x%02x" % (r, g, b), (x-x1, y-y1))
    picture.write('new_image.gif', format='gif')

Also, the line tuple(map(int, value.split(" "))) in your getRGB function is wrong, as value is already the tuple you want to create, not a string.1) As you can see, I just 'inlined' that part directly into the box function. Another problem was that you wrote the copied pixels to x and y, but you have to write them to x-x1 and y-y1 instead.

Update 1: 1) It seems like the return value of PhotoImage.get depends on the version of Python/Tkinter you are using. In some versions, it returns a tuple, like (41, 68, 151), and in others, a string, like u'41 68 151'.

Update 2: As pointed out by @Oblivion, you can in fact just use the from_coords parameter of PhotoImage.write to specify the region of the picture to be saved to file. With this, the box function can be simplified as

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)
    photo.write('new_image.gif', format='gif', from_coords=[x1, y1, x2, y2])
Answer from tobias_k on Stack Overflow
🌐
GitHub
gist.github.com › yohanesgultom › 630a831eff1fbdcd84b3cfec6feabe02
Random python scripts · GitHub
Random python scripts. GitHub Gist: instantly share code, notes, and snippets.
🌐
OneCompiler
onecompiler.com › python › 3wsj7ajyg
Python Online Compiler & Interpreter
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast.
Discussions

Copying and pasting code directly into the Python interpreter - Stack Overflow
There is a snippet of code that I would like to copy and paste into my Python interpreter. Unfortunately due to Python's sensitivity to whitespace it is not straightforward to copy and paste it a way More on stackoverflow.com
🌐 stackoverflow.com
Free recommended code sharing sites?
I’m fairly new to Python, I still have not finished my first Python tutorial. Sometimes it’s easier to share longer code (50+ lines) on a code sharing website. Besides pastebin.com, what are recommended code sharing sites when asking questions on a forum about Python? More on discuss.python.org
🌐 discuss.python.org
7
0
February 16, 2024
Copy and Paste Files - Command
Good night people, I have a problem, I used the following code to copy and paste files from one folder to another import os import time import shutil origem = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta2" destino = r"C:\Program Files\Corel\CorelDRAW Graphics Suite ... More on discuss.python.org
🌐 discuss.python.org
3
0
June 24, 2024
Is there a website where I can easily copy and paste python programs?
The problem I have with GITHUB is the file download, because I can't figure out how to get the code from the files. maybe learn how to do it? More on reddit.com
🌐 r/learnpython
4
0
May 27, 2022
People also ask

Is the Python code generator free to use?
Yes. You can generate Python code for free without creating an account for up to 2 generations per day. For more generations and higher limits, sign in for free — every account gets 5 free credits with support for up to 25,000 characters in your prompt per generation.
🌐
codeconvert.ai
codeconvert.ai › home › ai code generator › python code generator
Free Python Code Generator - AI-Powered | CodeConvert AI
Do I need to sign up to use the Python code generator?
No. You can use the free Python code generator without signing up or creating an account for up to 2 generations per day. Just describe what you need, and click Generate. Sign in for free to get 5 free credits with higher limits.
🌐
codeconvert.ai
codeconvert.ai › home › ai code generator › python code generator
Free Python Code Generator - AI-Powered | CodeConvert AI
Can I convert the generated Python code to another language?
Yes! After generating your Python code, you can use our free Code Converter tool to translate it to any of 50+ other programming languages with a single click.
🌐
codeconvert.ai
codeconvert.ai › home › ai code generator › python code generator
Free Python Code Generator - AI-Powered | CodeConvert AI
Top answer
1 of 2
2

The main problem with your code is that you create a new PhotoImage for each pixel! Instead, create the PhotoImage once and just add the pixels in the double-for-loop.

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)

    picture = PhotoImage(width=(x2-x1), height=(y2-y1))
    for x in range(x1, x2):
        for y in range(y1, y2):
            r, g, b = photo.get(x, y)
            picture.put("#%02x%02x%02x" % (r, g, b), (x-x1, y-y1))
    picture.write('new_image.gif', format='gif')

Also, the line tuple(map(int, value.split(" "))) in your getRGB function is wrong, as value is already the tuple you want to create, not a string.1) As you can see, I just 'inlined' that part directly into the box function. Another problem was that you wrote the copied pixels to x and y, but you have to write them to x-x1 and y-y1 instead.

Update 1: 1) It seems like the return value of PhotoImage.get depends on the version of Python/Tkinter you are using. In some versions, it returns a tuple, like (41, 68, 151), and in others, a string, like u'41 68 151'.

Update 2: As pointed out by @Oblivion, you can in fact just use the from_coords parameter of PhotoImage.write to specify the region of the picture to be saved to file. With this, the box function can be simplified as

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)
    photo.write('new_image.gif', format='gif', from_coords=[x1, y1, x2, y2])
2 of 2
0
import tkinter
from tkinter import *
import base64

root = Tk()

def action(canvas):
    canvas.bind("<Button-1>", xaxis)
    canvas.bind("<ButtonRelease-1>", yaxis)
    canvas.bind("<ButtonRelease-1>", box)

def xaxis(event):
    global x1, y1
    x1, y1 = (event.x - 1), (event.y - 1)
    print (x1, y1)

def yaxis(event):
    global x2, y2
    x2, y2 = (event.x + 1), (event.y + 1)
    print (x2, y2)

def box(event, photo):
    x1, y1 = (event.x - 1), (event.y - 1)
    x2, y2 = (event.x + 1), (event.y + 1)
    canvas.create_rectangle(x1, y1, x2, y2)
    new_photo = copy_photo(photo, x1, y1, x2, y2)
    new_photo.write('new_image.gif', format='gif')

def copy_photo(photo, x1, y1, x2, y2):
    new_photo = PhotoImage(width=photo.width(), height=photo.height())
    for x in range(photo.width()):
        for y in range(photo.height()):
            if x1 <= x < x2 and y1 <= y < y2:
                r,g,b = getRGB(photo, x, y)
                new_photo.put("#%02x%02x%02x" % (r,g,b), (x,y))
            else:
                new_photo.put(photo.get(x, y), (x,y))
    return new_photo

def getRGB(photo, x, y):
    value = photo.get(x, y)
    return tuple(map(int, value.split(" ")))

canvas = Canvas(width=500, height=250)
canvas.pack(expand=YES, fill=BOTH)
photo = PhotoImage(file="picture.gif")
canvas.create_image(0, 0, image=photo, anchor=NW)
canvas.config(cursor='cross')
action(canvas)

enter code here

canvas.mainloop()
🌐
Python Morsels
pythonmorsels.com › paste
Share Python Code – a runnable Pastebin
A free Python-oriented pastebin service for sharing Python code snippets with anyone
🌐
Java Code Geeks
javacodegeeks.com › home › web development › python
Explore These 20 Cool Python Scripts for Fun and Productivity! - Java Code Geeks
January 17, 2024 - Explore a collection of versatile Cool Python scripts, from web scraping to machine learning and web development.
Find elsewhere
🌐
Python
wiki.python.org › moin › SimplePrograms
SimplePrograms - Python Wiki
import unittest def median(pool): copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[int((size - 1) / 2)] else: return (copy[int(size/2 - 1)] + copy[int(size/2)]) / 2 class TestMedian(unittest.TestCase): def testMedian(self): self.assertEqual(median([2, 9, 9, 7, 9, 2, 4, 5, ...
🌐
GitHub
gist.github.com › sanchitgangwar › 2158089
Snakes Game using Python · GitHub
Snakes Game using Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Python.org
discuss.python.org › python help
Free recommended code sharing sites? - Python Help - Discussions on Python.org
February 16, 2024 - I’m fairly new to Python, I still have not finished my first Python tutorial. Sometimes it’s easier to share longer code (50+ lines) on a code sharing website. Besides pastebin.com, what are recommended code sharing site…
🌐
CodeConvert AI
codeconvert.ai › home › ai code generator › python code generator
Free Python Code Generator - AI-Powered | CodeConvert AI
Yes. You can generate Python code for free without creating an account for up to 2 generations per day. For more generations and higher limits, sign in for free — every account gets 5 free credits with support for up to 25,000 characters in ...
🌐
Python.org
discuss.python.org › python help
Copy and Paste Files - Command - Python Help - Discussions on Python.org
June 24, 2024 - Good night people, I have a problem, I used the following code to copy and paste files from one folder to another import os import time import shutil origem = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta2" destino = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta1" def copy_files(origem, destino): os.makedirs(destino, exist_ok=True) for item in os.listdir(origem): origem_arquivo = os.path.join(origem, item) destino_ar...
🌐
Medium
medium.com › @zhongwei2049 › 8-delightful-python-scripts-to-brighten-your-day-5908c1761905
8 Delightful Python Scripts to Brighten Your Day | by Zhongwei | Medium
July 30, 2023 - You can use Python to check if a website is up and running normally. # pip install requests #method 1 import urllib.request from urllib.request import Request, urlopenreq = Request('https://medium.com/@vesper7', headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).getcode() print(webpage) # 200 # method 2 import requests r = requests.get("https://medium.com/@vesper7") print(r.status_code) # 200
🌐
CodeRivers
coderivers.org › blog › text-code-to-copy-and-paste-into-python
Working with Text Code to Copy and Paste into Python - CodeRivers
February 22, 2026 - Text Editors: If you're working with a text editor that has Python code, you can also use the same selection and copy methods as above. Some text editors also offer additional features like code highlighting, which can make it easier to identify the code you want to copy. Interactive Interpreter: In the Python interactive interpreter (which you can access by running python in the command line), you can paste the copied code using Ctrl+V (Windows/Linux) or Command+V (Mac).
🌐
Grant Jenks
grantjenks.com › docs › freegames
Free Python Games — Free Python Games 2.5.3 documentation
$ python3 -m freegames copy snake $ python3 snake.py · Python includes a built-in text editor named IDLE which can also execute Python code. To launch the editor and make changes to the “snake” game run:
🌐
Reddit
reddit.com › r/python › share the code you're most proud of!
r/Python on Reddit: Share the code you're most proud of!
March 20, 2014 -

Well all know that sense of awesome when you write a neat, concise chunk of code that does something really cool. Take the code in the sidebar for example:

def fibonacci():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a + b

It's just a thought, but if you have a moment why not share your favorite snippet of code, along with a brief explanation? It must be under 10 lines, but anything else goes. Post away!

Top answer
1 of 5
96
It's not my most favourite but it can be handy now and again from __future__ import print_function import time class timer(object): def __init__(self, func=print): self.func = func def __enter__(self): self.time = time.time() def __exit__(self, type, value, traceback): total_time = time.time() - self.time self.func(total_time) If you want to know how long some code takes to run just use with timer(): # do something and it will print out how long it took to finish whatever it was that you wanted to do. It can also take in a function as an argument time_taken = [] for i in range(1000000): with timer(time_taken.append) # do something this will add the amount of time taken each time to a list and the average time can be obtained in a similar fashion to timeit. EDIT: Added time and print_function imports as suggested below. Also this should really only be used for rough timings or where what is being timed takes milliseconds and longer to compute to account for the extra overheads involved
2 of 5
68
Generating all valid clauses of a CFG specified as BNF from itertools import chain, product from re import match, findall GRAMMAR = ''' ::= ::= "boy " | "troll " | "moon " | "telescope " ::= "hits " | "sees " ::= "runs " | "sleeps " ::= "big " | "red " ::= "quickly " | "quietly " ::= "a " | "that " | "each " | "every " ::= "he " | "she " | "it " ::= | ::= | ''' def parse(g): return dict([(w.strip(), [findall(r'(<.+?>|".+?")', s) for s in m.split('|')]) for w, m in [d.split('::=') for d in g.strip().splitlines()]]) def generate(term): return findall(r'"(.*?)"', term) if match('".*', term) else chain(*[map(''.join, product(*map(generate, p))) for p in syntax[term]]) syntax = parse(GRAMMAR) print list(generate(''))
🌐
Anirudh Jayaraman
pythonandr.com › 2015 › 05 › 16 › code-for-my-first-text-based-game
Code for my First Text-Based Game – Anirudh Jayaraman
July 6, 2015 - Here’s the python code for this text-based game you might want to try out. You can simply copy the code below into a text file, naming it something like game.py and save it to your home directory or wherever you wish to and run game.py from. Then from Terminal (CMD for Windows), type in python game.py.
🌐
W3Schools
w3schools.com › python › python_lists_copy.asp
Python - Copy Lists
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
🌐
ActiveState
code.activestate.com › recipes › 578816-the-game-of-tic-tac-toe-in-python
The Game of Tic Tac Toe in Python « Python recipes « ActiveState Code
January 31, 2014 - Classic game but lacking in graphics :P Check out Tic-tac-toe in Free Python Games at http://www.grantjenks.com/docs/freegames/ You can just do "python3 -m pip install freegames" and then "python3 -m freegames.tictactoe" That includes a complete visual interface in just 57 lines of Python code!