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
🌐
Python
wiki.python.org › moin › SimplePrograms.html
SimplePrograms
>>> median([2, 9, 9, 7, 9, 2, 4, 5, 8]) 6 #change to 7 in order to pass the test ''' 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 if __name__ == '__main__': import doctest doctest.testmod() ...
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()
Discussions

Share the code you're most proud of!
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 More on reddit.com
🌐 r/Python
264
181
March 20, 2014
Massive Python Example Script - General and Gameplay Programming | GameDev.net Forums - GameDev.net
TL;DR I am trying to make a massive example script, demonstrating all of the core syntax of Python (beginner to intermediate and maybe advanced). It could serve as a tutorial … More on gamedev.net
🌐 gamedev.net
July 29, 2015
Hello guys how do i copy/paste code on reddit if i have problem ?

Click 'formatting help'.

More on reddit.com
🌐 r/learnpython
5
0
March 7, 2017
What's the coolest thing you did with Python?
Hello everyone. I'm a beginner in Python and still doing a course on it. I just started Python just 2 months. I really want… More on reddit.com
🌐 r/Python
416
356
April 2, 2018
🌐
Programiz
programiz.com › python-programming › examples
Python Examples | Programiz
This page contains examples of basic concepts of Python programming like loops, functions, native datatypes and so on.
🌐
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.
🌐
GitHub
github.com › geekcomputers › python
GitHub - geekcomputers/Python: My Python Examples · GitHub
I would gladly accept pointers from others to improve, simplify, or make the code more efficient. If you would like to make any comments then please feel free to email me: craig@geekcomputers.co.uk. This repository contains a collection of Python scripts that are designed to reduce human workload and serve as educational examples for beginners to get started with Python.
Author   geekcomputers
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-programming-examples
Python Programs - Python Programming Example - GeeksforGeeks
May 23, 2026 - The below Python section contains a wide collection of Python programming examples. These Python code examples cover a wide range of basic concepts in the Python language, including List, Strings, Dictionary, Tuple, sets and many more.
Find elsewhere
🌐
Medium
medium.com › coders-camp › 60-python-projects-with-source-code-919cd8a6e512
60 Python Projects with Source Code | by Aman Kharwal | Coders Camp | Medium
May 11, 2021 - Python has been in the top 10 popular programming languages for a long time, as the community of Python programmers has grown a lot due to its easy syntax and library support. In this article, I will introduce you to 60 amazing Python projects with source code solved and explained for free.
🌐
AskPython
askpython.com › python › examples › easy-games-in-python
Easy Games in Python - AskPython
April 20, 2026 - Python is one of the easiest languages for building your own games. You can start with text-based games using only print() and input(), then move to graphical games using the built-in turtle module or install pygame via pip install pygame. A number guessing game or a Quiz Game are the easiest starting points. Both require under 50 lines of code, use only built-in functions, and teach you core concepts like loops, conditionals, and player input.
🌐
freeCodeCamp
freecodecamp.org › news › python-code-examples-sample-script-coding-tutorial-for-beginners
Python Code Example Handbook – Sample Script Coding Tutorial for Beginners
April 27, 2021 - Hi! Welcome. If you are learning Python, then this article is for you. You will find a thorough description of Python syntax and lots of code examples to guide you during your coding journey. What we will cover: Variable Definitions in Python Hello...
🌐
Advanced ICT
advanced-ict.info › home › programming › python examples
Python Examples | Programming | Computing
Most programs open in Basthon, ... Where a program doesn't run in Basthon (e.g. because it uses the turtle) then the link opens the code, which you can copy and paste into your own IDE....
🌐
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 - I tried running script #3 by cutting and pasting the code into my VSC IDE, and received these errors: Traceback (most recent call last): File “c:\Users\bromberg.DESKTOP-V44B91G\OneDrive\Desktop\Python-quickies\Python_drbVScode\hashlib.py”, line 1, in import hashlib File “c:\Users\bromberg.DESKTOP-V44B91G\OneDrive\Desktop\Python-quickies\Python_drbVScode\hashlib.py”, line 17, in blockchain = [Block(“0”, “Genesis Block”)] ~~~~~^^^^^^^^^^^^^^^^^^^^^^ File “c:\Users\bromberg.DESKTOP-V44B91G\OneDrive\Desktop\Python-quickies\Python_drbVScode\hashlib.py”, line 9, in __init__ self.
🌐
Hackr
hackr.io › home › articles › projects
Top 40 Python Projects for Programmers (Beginner to Advanced)
February 19, 2026 - Explore 40+ hands-on Python projects, from beginner-friendly automation to professional portfolio applications, with step-by-step tutorials and video walkthroughs.
🌐
Learn Python
learnpython.org › en › Hello,_World!
Hello, World! - Learn Python - Free Interactive Python Tutorial
It encourages programmers to program without boilerplate (prepared) code. The simplest directive in Python is the "print" directive - it simply prints out a line (and also includes a newline, unlike in C). There are two major Python versions, Python 2 and Python 3. Python 2 and 3 are quite different. This tutorial uses Python 3, because it more semantically correct and supports newer features. For example, one difference between Python 2 and 3 is the print statement.
🌐
Codingal
codingal.com › coding-for-kids › blog › python-projects-beginners
Top 10 Python Projects for Beginners to Build and Learn
March 20, 2026 - In this guide, you will find 18 beginner-friendly Python projects that are fun to make and useful for learning. Each project includes a short explanation, a difficulty label (Beginner or Intermediate), an estimated completion time, and a working code example to help you get started.
🌐
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(''))
🌐
OneCompiler
onecompiler.com › python › 3wsj7ajyg
Python Online Compiler & Interpreter
The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
🌐
XWord Info
xwordinfo.com › Python
Sample Python scripts
Once you have a Python environment set up on your computer, you can copy and paste this script, change the "open" statement to point to your text file, and run it to find all the words that start and end with "x" or with the string "de" or whatever. That's a very specific example, but to find the words you're looking for, all you have to do is replace the test at the end (if word.startswith...) with logic that fits your goal.
🌐
GameDev.net
gamedev.net › home › forums › programming › general and gameplay programming › massive python example script
Massive Python Example Script - General and Gameplay Programming | GameDev.net Forums - GameDev.net
July 29, 2015 - There will be much more commenting in the file, but for now: # -*- coding: utf-8 -*- print "Python Examples\n --By The Tutorial Doctor\n" print ("Remove tripple quotes around each secrion to test the code therein" ) ## PRINTING #--------------------------------------------------------------------- """ print 'Hello' print 'Hello','Editorial' # Concatenate/Append text (gives errors if not strings) print 'Hello' + 'Folks' print 'Hello' + ' Folks' # have to add your own space print 27 """ #--------------------------------------------------------------------- # VARIABLES #--------------------------------------------------------------------- #There are different types of variables: character, string, integer, float, boolean, array/list, dictionary, and a few others.
🌐
Python documentation
docs.python.org › 3 › tutorial › introduction.html
3. An Informal Introduction to Python — Python 3.14.6 documentation
You can use the “Copy” button (it appears in the upper-right corner when hovering over or tapping a code example), which strips prompts and omits output, to copy and paste the input lines into your interpreter.