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
🌐
Reddit
reddit.com › r/learnpython › 100% complete noob trying to copy/paste code
r/learnpython on Reddit: 100% complete noob trying to copy/paste code
September 12, 2021 -

[SOLVED]

Yo. Please use the most dumbed down language, because I've literally never done this stuff, Idk how python works. And at this moment, I'm not exactly trying to. Im just trying to copy/paate a command. I am simply trying to copy/paste code from a guide and it keeps saying I have a syntax error. I think I figured out that you dont actually type the $, but I dont even know if that's correct. Either way, I continue to get a syntax error with the arrow pointing to seemingly random letters.

Please help.

Edit: This is the simple command given to download a HTTP library for Python called "Requests":

$ python -m pip install requests

Edit2: Thanks to social_nerdtastic for answering. I just had to use cmd. I had a feeling it was something simple and fundamental that I just didn't know

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

Copying and pasting code directly into the Python interpreter - Stack Overflow
You can simply convert all tabs to spaces and remove ALL empty lines. So you will be able to paste any code to python console (e.g.: python2.6) ... Save this answer. ... Show activity on this post. You can call execfile(filename). More or less the same as importing a module, except that it skips the module administration part and doesn't require you to add a folder to sys.path. Copy... More on stackoverflow.com
🌐 stackoverflow.com
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
Complete noob, need copy/paste code
Yo. I have a single task I need to have python complete, and I’m looking for a code that I can copy and paste into Python and just change the parameters of the command. More on reddit.com
🌐 r/learnpython
6
0
December 6, 2024
Basic Python for copy/pasting files in windows | Forums | SideFX
Forums Technical Discussion Basic Python for copy/pasting files in windows ... July 24, 2023 1:15 p.m. Hi! I've got a few SpeeTree assets that I modifed with my HDA. The last thing I can't do is copy/paste all the textures into a specific folder hierarchy and rename those copied files. More on sidefx.com
🌐 sidefx.com
🌐
YouTube
youtube.com › watch
simple python code copy and paste - YouTube
Instantly Download or Run the code at https://codegive.com title: simple python code copy and paste tutorialintroduction:copying and pasting code is a commo...
Published   February 23, 2024
🌐
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, ...
🌐
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.
🌐
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...
Find elsewhere
🌐
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 - 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). However, be aware that some complex code structures may need to be adjusted slightly for proper execution in the interpreter. # Pasting a simple variable assignment in the interpreter x = 5 print(x)
🌐
Reddit
reddit.com › r › learnpython › comments › 1h7rovv › complete_noob_need_copypaste_code
Complete noob, need copy/paste code : r/learnpython
December 6, 2024 - ChatGPT told me to use Python to do this, but I don’t know anything about coding and I will literally never use it again, so I don’t need to learn coding. If anyone could PLEASE tell me where to find a “template”, for lack of a better term, that would accomplish this task, I would forever be grateful. Thank you! ... Create your account and connect with a world of communities.
🌐
Backlinkworks
blogs.backlinkworks.com › home › copy and paste your way to a fun python game with this simple code!
Copy and Paste Your Way to a Fun Python Game with This Simple Code! - Topics on SEO & Backlinks
November 8, 2023 - Simply copy and paste the above code into a Python IDE or text editor, and you’ll have a working Rock, Paper, Scissors game ready to go!
🌐
CopyAssignment
copyassignment.com › python-games-code-copy-and-paste
Python Games Code | Copy and Paste – CopyAssignment
August 23, 2022 - Hello friends, today, we will see all the Python games code which you can easily copy and paste into your system.
🌐
GitHub
gist.github.com › sanchitgangwar › 2158089
Snakes Game using Python · GitHub
Snakes Game using Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
SideFX
sidefx.com › forum › topic › 91255
Basic Python for copy/pasting files in windows | Forums | SideFX
def foo(): import os # Read the texture folder path from node parameters (pwd is shortcut for hou.node(".") (current node)) folder_path = hou.pwd().parm("txt_fld").eval() # Insert all texture paths contained in the folder into a list file_list = [os.path.join(folder_path, file) for file in os.listdir(folder_path)] print(file_list) this will return the paths of the contents specified by the parm file dictionary. The last thing you need to do is to bind the foo() function to the button. Go back to the parameters tab, select your button, and under Callback Script, paste this snippet:
🌐
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.
🌐
XWord Info
xwordinfo.com › Python
Sample Python Scripts, aka Fun with Word Lists
Here's a simple script you can use as a template for exploring your own word list, whether you got it from us or you built it yourself. 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 ...
🌐
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 - Python · Tcl · Komodo IDE | more ▼ · Lists · Support · PPM Index · PyPM Index · Welcome, guest | Sign In | My Account | Store | Cart · ActiveState Code » Recipes · Languages Tags Authors Sets · I thought this is a fun game to program. Easy to program and can teach a lot. Captain DeadBones · Copy to Clipboard ·
🌐
Normngyn
normngyn.com › python › how-to-copypasterun-codes
Norm's Portal - How to Copy/Paste/Run Codes
I have created the codes for learning all 50 state capitals besides others. Check the "Simple Copy-and-Paste Codes" tab at the top of my website. Click Learning State Capitals. There you can highlight it to copy and paste it to Python.
🌐
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.