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
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_lists_copy.asp
Python - Copy Lists
Python Operators Arithmetic Operators ... Bitwise Operators Operator Precedence Code Challenge Python Lists ยท Python Lists Access List Items Change List Items Add List Items Remove List Items Loop Lists List Comprehension Sort Lists Copy Lists Join Lists List Methods List Exercises ...
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ SimplePrograms.html
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, ...
Discussions

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
image - "copy and paste" python program - Stack Overflow
I'm currently trying to write a program that reads a GIF file, displays its image on the screen, then allows the user to select a rectangular portion of the image to "copy and paste", AKA to then c... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
100% complete noob trying to copy/paste code
You can't do that! To understand where the syntax error is, you have to know what it is! You can't just copy paste random codes from different places and make a program out of that. I want to help you, but you'll need to study my help. Look for asset lines, lines that mark a file, if you don't have the file, your program won't recognize it. Also look for missing modules, you may be using commands from a module you don't have or that you didn't activated. To activate a module write 'from (module) import *'. You have to download a module before trying that. Look for wrong spaces too, copy/paste is dangerous because of spaces, between symbols. That's why I don't recommend it More on reddit.com
๐ŸŒ r/learnpython
22
0
September 12, 2021
๐ŸŒ
GitHub
gist.github.com โ€บ yohanesgultom โ€บ 630a831eff1fbdcd84b3cfec6feabe02
Random python scripts ยท GitHub
To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ... I leave my grain of rice. I just was bored and I feel inspired by this https://craft.js.org/docs/overview#extensible ... from __future__ import annotations import copy import ctypes import uuid from typing import Any, Callable # ============================== # react.py # ============================== class Temp: ...
๐ŸŒ
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...
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()
๐ŸŒ
GitHub
gist.github.com โ€บ sanchitgangwar โ€บ 2158089
Snakes Game using Python ยท GitHub
Snakes Game using Python. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
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
๐ŸŒ
Board Infinity
boardinfinity.com โ€บ blog โ€บ copy-in-python
Copy in Python | Board Infinity
August 9, 2025 - In Python, we use copy module to make a clone or real copy of an object. This module consists of two methods: copy(): This method returns a shallow copy of the list. deepcopy(): This method returns a deep copy of the list. Code ยท Output ยท As we can see above, the IDs of list 2 and list 3 are different but the list is the same.
๐ŸŒ
OneCompiler
onecompiler.com โ€บ python โ€บ 3wsj7ajyg
Python Online Compiler & Interpreter
OneCompiler's Python online editor helps you to write, interpret, run and debug python code online. Libraries for data science and machine learning are also available
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_list_copy.asp
Python List copy() Method
Python Operators Arithmetic Operators ... Bitwise Operators Operator Precedence Code Challenge Python Lists ยท Python Lists Access List Items Change List Items Add List Items Remove List Items Loop Lists List Comprehension Sort Lists Copy Lists Join Lists List Methods List Exercises ...
๐ŸŒ
Normngyn
normngyn.com โ€บ python โ€บ how-to-copypasterun-codes
Norm's Portal - How to Copy/Paste/Run Codes
Find the Python directory/folder in the programs area or if you've already made a shortcut on your desktop, find "IDLE" and run it. This is a shortcut placed on the PC desktop. Sometimes during an app installation, it will place the executable shortcut on your desktop. If not, you can find the executable and place it on your desktop. Once you run Idle, go to File, dropdown and click on New File. Copy the codes given to you from me, a friend etc., and then Paste them in the blank page.
๐ŸŒ
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

๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ list โ€บ copy
Python List copy()
# copy list using = new_list = old_list # add an element to list new_list.append('a') print('New List:', new_list) print('Old List:', old_list) ... However, if you need the original list unchanged when the new list is modified, you can use the copy() method. Related tutorial: Python Shallow Copy Vs Deep Copy
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-copy-list
Python Copy List: What You Should Know | DataCamp
August 13, 2024 - Understand how to copy lists in Python. Learn how to use the copy() and list() functions. Discover the difference between shallow and deep copies.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_copy.asp
Python - Copy Dictionaries
Python Sets Access Set Items Add Set Items Remove Set Items Loop Sets Join Sets Frozenset Set Methods Set Exercises Code Challenge Python Dictionaries ยท Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else
๐ŸŒ
CodeConvert AI
codeconvert.ai โ€บ home โ€บ ai code generator โ€บ python code generator
Free Python Code Generator - AI-Powered | CodeConvert AI
Describe the Python function, script, or program you want in plain English. ... Click Generate to turn your instructions into source code. ... Review, copy, or download the generated Python code from the output editor.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ paste
Share Python Code โ€“ a runnable Pastebin
A free Python-oriented pastebin service for sharing Python code snippets with anyone
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
copying example code into idle - Raspberry Pi Forums
I'll try this tomorrow on the Pi and take it from there. I have had this problem before, even copying examples from the Raspberry Pi education manual. ... Gerry, Hope you get it up and running well. ... pi@raspberrypi ~ $ cat > gerry2.py #!/usr/bin/python class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary "This would create first object