Python 3.3 TKinter image doesn't exist - python

I am trying to open an image with ImageTk.PhotoImage from PIL but I keep hitting the same error. I have the image and can see that it is there when it downloads it, it opens it, but then I get the error that it is not there.
Here is the error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "S:/Projects/xmlParser.py", line 128, in updateSelected
self.threadLabelImage.config(text = self.threadImage)
File "C:\Python33\lib\tkinter\__init__.py", line 1263, in configure
return self._configure('configure', cnf, kw)
File "C:\Python33\lib\tkinter\__init__.py", line 1254, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist
Relevant Code
if self.threadLinkList[self.y].find('imgur') != -1:
url = self.threadLinkList[self.y]+'.gif'
imageName=self.threadLinkList[self.y][-11:-4]+'.gif'
print(imageName)
urllib.request.urlretrieve(self.threadLinkList[self.y],imageName)
imgfile = Image.open(imageName)
imgfile = imgfile.resize((150,150),Image.ANTIALIAS)
# img = Image.open(file)
print(imgfile)
self.threadImage = ImageTk.PhotoImage(imgfile)
self.threadLabelImage.config(text = self.threadImage)
self.threadImage.image = imgfile
Entire program to run.
import xml.etree.ElementTree as ET
import webbrowser,time,urllib.request,re,os
import tkinter as tk
import urllib
from PIL import Image,ImageTk
main = tk.Tk()
os.getcwd()
class Application(tk.Frame):
def __init__(self, master=None):
self.threadTitle = tk.StringVar()
self.threadAuth = tk.StringVar()
self.threadPub = tk.StringVar()
self.threadArtLink = tk.StringVar()
self.threadLink = tk.StringVar()
self.threadImg = tk.StringVar()
self.threadArtLink.set('Click something to display thread info')
photo = Image.open("temp.png")
photo = photo.resize((150,150), Image.ANTIALIAS)
self.threadImage = ImageTk.PhotoImage(photo)
# Intializes tkinter gui framework
tk.Frame.__init__(self, master)
# Packs widgets needed
self.grid()
# Creates the widgets functions
self.createWidgets()
# Intializes the man rss.xml
self.initial()
# self.threadLabelArtLink = None
# self.threadLabelTitle = None
# self.threadLabelThreadLink = None
# self.threadLabelArtLink = None
# self.threadImgLink = None
def createWidgets(self):
# Create entrybox and align to grid
self.send_entry = tk.Entry(self)
self.send_entry.grid(row=0,column=0)
# Create button,allign to grid, get xml
self.change_sub = tk.Button(self,text='Change Subreddit',padx=5, pady=5, command=lambda :self.getXML(self.send_entry.get()))
self.change_sub.grid(row=0 , column=3)
# Create scrollbar on Y-Axis
self.lb_scrollY = tk.Scrollbar(self,orient=tk.VERTICAL)
# On grid next to Listbox(sticky means fill whole row
self.lb_scrollY.grid(row=1,column=4,sticky=tk.NS,rowspan=6)
# Create Listbox and get Y from scrollbar
self.thread_lb = tk.Listbox(self,yscrollcommand=self.lb_scrollY.set,height=20)
# Calls function whenever a new item is selected & open thread if double click 1
self.thread_lb.bind('<<ListboxSelect>>',self.updateSelected)
self.thread_lb.bind('<Double-Button-1>',self.openPage)
# scrolly will change the view of listbox
self.lb_scrollY['command']=self.thread_lb.yview
self.thread_lb.grid(row=1,column=0,sticky=tk.NS+tk.EW,columnspan=4)
self.threadFrame = tk.LabelFrame(main,text='Reddit',width=450,height=350,labelanchor='n')
self.threadLabelTitle = tk.Label(self.threadFrame,textvariable=self.threadTitle,wraplength=400,padx=20, pady=5)
self.threadLabelTitle.grid(row=1,column=10,sticky= tk.EW)
self.threadLabelAuth = tk.Label(self.threadFrame, textvariable=self.threadAuth,wraplength=400,padx=20, pady=5)
self.threadLabelAuth.grid(row=2,column=10,sticky = tk.EW)
self.threadLabelPub = tk.Label(self.threadFrame, textvariable=self.threadPub,wraplength=400,padx=20, pady=5)
self.threadLabelPub.grid(row=3,column=10,sticky = tk.EW)
self.threadLabelArtLink = tk.Label(self.threadFrame, textvariable=self.threadArtLink,wraplength=400,padx=20, pady=5)
self.threadLabelArtLink.grid(row=4,column=10,sticky = tk.EW)
self.threadLabelThreadLink = tk.Label(self.threadFrame, textvariable=self.threadLink,wraplength=400,padx=20, pady=5)
self.threadLabelThreadLink.grid(row=5,column=10,sticky = tk.EW)
self.threadImgLink = tk.Label(self.threadFrame, textvariable=self.threadImg,wraplength=400,padx=20, pady=5)
self.threadImgLink.grid(row=6,column=10,sticky = tk.EW)
self.threadLabelImage = tk.Label(self.threadFrame,image=self.threadImage,wraplength=400,padx=20,pady=5)
self.threadLabelImage.grid(row=7,column=10,sticky = tk.EW)
self.threadFrame.grid(row=0,column=10,sticky=tk.EW,rowspan=8)
self.QUIT = tk.Button(self, text="QUIT", fg="red", command=main.destroy,padx=5, pady=5)
self.QUIT.grid(row=7)
self.threadFrame.grid_propagate(0)
def updateSelected(self, event):
# getting selected listbox item
i=self.thread_lb.curselection()
# Returns tuple that must be split
x,self.y,z = re.split("\D+",str(i))
self.y=int(self.y)
print(self.threadTitleList[self.y])
print(self.threadPubDateList[self.y])
print(self.threadLinkList[self.y])
print(self.threadDescList[self.y])
self.threadTitle.set(self.threadTitleList[self.y])
self.threadAuth.set(self.threadAuthList[self.y])
self.threadPub.set(self.threadPubDateList[self.y])
self.threadArtLink.set(self.threadLinkList[self.y])
self.threadLink.set(self.threadDescList[self.y])
# self.threadImg.set('Will put image here')
if self.threadLinkList[self.y].find('imgur') != -1:
url = self.threadLinkList[self.y]+'.gif'
imageName=self.threadLinkList[self.y][-11:-4]+'.gif'
print(imageName)
urllib.request.urlretrieve(self.threadLinkList[self.y],imageName)
imgfile = Image.open(imageName)
imgfile = imgfile.resize((150,150),Image.ANTIALIAS)
# img = Image.open(file)
print(imgfile)
self.threadImage = ImageTk.PhotoImage(imgfile)
self.threadLabelImage.config(text = self.threadImage)
self.threadImage.image = imgfile
# # threadTitle = self.threadTitleList[y]
# print(self.threadLabelTitle["text"])
# # self.threadLabelTitle['text']=threadTitle
# self.threadLabelAutPub['text']=self.threadPubDateList[y]
# self.threadImgLink['text']=self.threadLinkList[y]
# self.threadLabelThreadLink['text']=self.threadDescList[y]
# main.update()
def openPage(self,event):
webbrowser.get('windows-default').open_new(self.threadLinkList[self.y])
def descStripper(self,desc):
# Intialize values
l1,l2,l2Start = 0,0,0
t1,t2,t2start = 0,0,0
link = ""
thread = ""
# Where to start looking for each in description element
l1=int(desc.find('<br/> <a href="'))
t1=int(desc.find('</a> <a href="'))
a1=int(desc.find('"> '))
# If both of the tags are found then continue
if l1 != -1 and t1 != -1 and a1 != 1:
# Start looking for end of quotes 16 characters from beginning of tag
l2Start = l1+16
l2=int(desc.find('"',l2Start))
# Link is created from what is in the quotes
link = desc[l1+15:l2]
# Same as above but to find thread link
t2start = t1+15
t2=int(desc.find('"',t2start))
thread = desc[t1+14:t2]
a2start = a1+4
a2 = int(desc.find(' <',a2start))
author = desc[a1+3:a2]
return link,thread,author
else:
# If it can't find one it will return an error
link = "Couldn't find the stuff :("
thread = "Couldn't find the thread link :("
return link, thread
def lbPopulator(self,title,pub,link):
# Delete old entries from listbox
self.thread_lb.delete(0,tk.END)
# Iterate through all the items and append them to the listbox
for item in title:
self.thread_lb.insert(tk.END,item)
def getXmlData(self):
# Intialize lists
self.threadPubDateList = []
self.threadTitleList = []
self.threadLinkList = []
self.threadDescList = []
self.threadThumbNailList = []
self.threadAuthList = []
# Use the downloaded rss.xml for XML parsing
tree=ET.parse('rss.xml')
# define root as the base of the XML parsing tree
root=tree.getroot()
for channel in root:
# Iterate through all the channels
for SubChannel in channel:
# Iterate through all the items in the channel
if SubChannel.tag == 'item':
# If the SubChannel is called item then search for the items below
for threadInfo in SubChannel:
# iterate through all the items in the 'item'
if threadInfo.tag == 'title':
# append the tag from the title to the list
self.threadTitleList.append(threadInfo.text)
if threadInfo.tag == 'pubDate':
# Append the pubdate info to the list but remove excess characters
self.threadPubDateList.append(threadInfo.text[:-6])
if threadInfo.tag == 'description':
# Pass all the information from the description to the stripper to get the useful
# information and links
link,thread,author = self.descStripper(threadInfo.text)
self.threadLinkList.append(link)
self.threadDescList.append(thread)
self.threadAuthList.append(author)
# if threadInfo.tag == ''
# Populate the listbox with the newly generated lists
self.lbPopulator(self.threadTitleList,self.threadPubDateList,self.threadLinkList)
def getXML(self,subreddit):
try:
# Try to download the xml file using the user input subreddit
url = 'http://www.reddit.com'+subreddit+'.rss'
source = urllib.request.urlretrieve(url,'rss.xml')
self.getXmlData()
except urllib.error.HTTPError as err:
# Error caused by reddit API limiting connections
print('Too many requests-Try again')
def initial(self):
try:
# Same as above but downloads the front page
source = urllib.request.urlretrieve('http://www.reddit.com/.rss','rss.xml')
self.getXmlData()
except urllib.error.HTTPError as err:
print('Too many requests-Trying again 3')
# If error occurs program waits 3 seconds and then restarts
time.sleep(3)
self.__init__()
# main.geometry("350x400")
app = Application(master=main)
# Begins the applications GUI loop
app.mainloop()

I was attempting to apply the image to the text attribute of the label instaed of the image. Here is the fixed code.
url = self.threadLinkList[self.y]+'.gif'
imageName=self.threadLinkList[self.y][-11:-4]+'.gif'
print(imageName)
urllib.request.urlretrieve(self.threadLinkList[self.y],imageName)
imgfile = Image.open(imageName)
imgfile = imgfile.resize((150,150),Image.ANTIALIAS)
# img = Image.open(file)
print(imgfile)
self.threadImage = ImageTk.PhotoImage(imgfile)
self.threadLabelImage.config(***image*** = self.threadImage)
self.threadImage.image = imgfile

Related

storing output text in a tkinter textbox

im looking to output a list of text to both a text file as well as a tkinter textbox. Currently I have it working to print to a text file being held in the same folder. I would like this same list to be printed on screen into the outputToScreen textbox
From my research I think I am meant to use .insert(index , text) but I can not get this method to work. I have also seen some old code using a .set function but when I tried this I came across an error saying that textbox's don't have that method
#file -> gui.py
# IMPORT tkinter for GUI creation and import scripts for functions
from tkinter import *
from tkinter.ttk import *
import scripts
import customtkinter
windowDim = str(750)+'x'+str(600)
window = customtkinter.CTk()
window.title("INFO GENERATOR")
window.geometry(windowDim)
window.resizable(True, True)
# Modes: system (default), light, dark
customtkinter.set_appearance_mode("dark")
# Themes: blue (default), dark-blue, green
customtkinter.set_default_color_theme("customTkinterTheme.json")
outputToScreen = customtkinter.CTkTextbox(window , width=400 , height=200)
outputToScreen.place(x=200, y=300)
def popupmsg(msg):
popup = customtkinter.CTk()
popup.title("!")
label = customtkinter.CTkLabel(popup, text=msg,)
label.pack(side="top", fill="x", pady=10)
B1 = customtkinter.CTkButton(popup, text="Okay", command=popup.destroy)
B1.pack()
popup.mainloop()
# create main window
# window specs are 700 x 350 and window is not able to be resizeable
# CREATING USER CONTROLS
# each button will print a list of items (number of items will be come from the entry userValue)
userEntry = customtkinter.CTkEntry(window)
# userValue = int(userValue)
userValue = ""
userEntry.place(x=325, y=200)
userEntry.insert(0, userValue)
userValueLabel = customtkinter.CTkLabel(
window, text="ENTER AMOUNT OF RECORDS YOU WOULD LIKE").place(x=275, y=170)
label = customtkinter.CTkLabel(window, text="INFOMATION GENERATOR by Noah Mackay "
).pack()
def outputEmails(userValue):
# function receives the amount of records the user wants to print
# function will be called when email button is clicked
# this function will clear the output file and then read open it
# will call the generateEmail function from scripts.py file
# outputs the amount of records based on the user input in the entry text box
userValue = int(userEntry.get())
outputFile = scripts.generateEmail(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING WORKED")
def outputNames(userValue):
# function receives the amount of records the user wants to print
# function will be called when email button is clicked
# this function will clear the output file and then read open it
# will call the generateEmail function from scripts.py file
# outputs the amount of records based on the user input in the entry text box
userValue = int(userEntry.get())
outputFile = scripts.generateName(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputCost(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generateCost(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputProduct(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generateProduct(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputPhoneNumber(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generatePhoneNumber(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.insert(0,outputFile)
popupmsg("PRINTING COMPLETED")
# creates 5 buttons each have their respective output function attached using command=
emailButton = customtkinter.CTkButton(window, text="EMAILS",
command=lambda: outputEmails(userValue)).place(x=5, y=40)
productButton = customtkinter.CTkButton(window, text="PRODUCTS",
command=lambda: outputProduct(userValue)).place(x=150, y=40)
phoneNumberButton = customtkinter.CTkButton(
window, text="PHONE NUMBERS" , command= lambda:outputPhoneNumber(userValue)).place(x=300, y=40)
costButton = customtkinter.CTkButton(window, text="PRICES",
command=lambda: outputCost(userValue)).place(x=450, y=40)
nameButton = customtkinter.CTkButton(
window, text="FIRST + LAST NAMES", command=lambda: outputNames(userValue)).place(x=600, y=40)
window.mainloop()
#file -> scripts.py
import random
def generateName(numberOfItemsNeed):
# opens 2 files. One containing first names and the other containing last names
firstNameFile = open('dataFiles\FirstNamesData.txt', 'r')
lastNameFile = open('dataFiles\LastNamesData.txt', 'r')
# builds values for the while statement and the return string
returnValue = ""
counter = 0
# builds the return string using a while loop and removing the newline character
# after each line from both files when being read
while counter < int(numberOfItemsNeed):
returnValue += str(firstNameFile.readline().strip("\n")
) + " " + str(lastNameFile.readline().strip("\n")) + "\n"
counter = counter + 1
# returns a list of "human" names in a single string divided by a newline character
return (returnValue)
def generateEmail(numberOfItemsNeed):
# opens a file containing a records of first names
firstNameFile = open('dataFiles\dictonary.txt', 'r')
counter = 0
# A list of commonly used email address suffixs
suffix = ['#gmail.com', '#gmail.ca', '#hotmail.com',
'#hotmail.ca', '#mail.com ', '#mail.ca', '#gov.ca']
returnValue = ""
while counter < int(numberOfItemsNeed):
returnValue += firstNameFile.readline().strip("\n") + \
str((random.randrange(0, 100))) + \
suffix[random.randrange(0, len(suffix))]+'\n'
counter = counter + 1
return (returnValue)
def generateCost(numberOfItemsNeed):
# generates a random item price in the inclusive range of 0.00$ to 1000.99$
counter = 0
cost = ""
while counter < int(numberOfItemsNeed):
cost += '$' + str(random.randrange(0, 1000)) + \
"." + str(random.randrange(0, 99)) + '\n'
counter = counter+1
return cost
def generateProduct(numberOfItemsNeed):
counter = 0
returnValue = ""
productList = open('dataFiles\itemData.txt', 'r')
while counter < int(numberOfItemsNeed):
returnValue += str(productList.readline()
).strip("\n") + str(generateCost(1))
counter = counter + 1
return (returnValue)
def generatePhoneNumber(numberOfItemsNeed):
counter = 0
returnValue = ""
while counter < int(numberOfItemsNeed):
firstNumber = str(random.randrange(100, 999))
secondNumber = str(random.randrange(1000, 9999))
thirdNumber = str(random.randrange(100, 999))
returnValue += firstNumber + "-" + secondNumber + "-" + thirdNumber + '\n'
counter = counter + 1
return (returnValue)
def shuffleFile(filePath):
lines = open(filePath).readlines()
random.shuffle(lines)
open(filePath, 'w').writelines(lines)
# shuffleFile('dataFiles\dictonary.txt')
Text widget indexes are strings of the form line.character with lines starting at 0 and characters starting at 1. So, to insert at the start you need to use the index "1.0", not 0. If you want to insert at the end you can use the special index "end". If the widget is empty, "1.0" and "end" yield identical results.
outputToScreen.insert("1.0", outputToFile)

Python Tkinter TextEditor how to save configuration changes

i'm very new to Tkinter but i tried to read all the documentation that i could and could not understand if i'm heading in the right direction or not.
Firstly, thank you for reading this.
In summary i'm trying to create a Text Editor with Tkinter. This text editor however must display the exact same file for every user which opens it in the same private network as it is to be used as a display Panel in order for everyone to be able to read anyone else's notices.
I Have still a lot to do but where i'm blocking right now and couldn't find an answer for is to be able to store the configurations changes that are applied to the text (Bold, color etc..)
the text itself is stored in a txt file that is automatically opened at the start of the program but i don't know a way to store the color and font style.
To apply the font and color to the text i use a counter that i apply to each tag change that is done (so the first area selection that will be changed will be named "colortag1" the second "colortag2" etc ..)
I don't know if it is possible to keep theses tags configurations and the count of my variable "counter" stored without reseting everything.
Would someone possibly have an idea?
I'm really sorry if it's not very understandable.
Here is my code:
import tkinter
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
class Notepad:
#Creation of a Notepad Class
__root = Tk()
__countG = 1
__thisWidth = 300
__thisHeight = 300
__thisTextArea = Text(__root)
__thisMenuBar = Menu(__root)
__thisFileMenu = Menu(__thisMenuBar, tearoff=0)
__thisEditMenu = Menu(__thisMenuBar, tearoff=0)
__thisScrollBar = Scrollbar(__thisTextArea)
#The file that is always opened by the notepad
__file = "//srvad/echange/Python panel/paneltest.txt"
__thisTextArea.configure(font=("arial", "12" ,"normal"))
def __init__(self, **kwargs):
try:
self.__root.wm_iconbitmap("Notepad.ico")
except:
pass
try:
self.__thisWidth = kwargs['width']
except KeyError:
pass
try:
self.__thisHeight = kwargs['height']
except KeyError:
pass
#Creation of Edit Cascade
self.__thisMenuBar.add_cascade(label="Edit",
menu=self.__thisEditMenu)
#Name of the text editor
self.__root.title("Home Panel")
#Size and settings of the Notepad
screenWidth = self.__root.winfo_screenwidth()
screenHeight = self.__root.winfo_screenheight()
left = (screenWidth / 2) - (self.__thisWidth / 2)
top = (screenHeight / 2) - (self.__thisHeight / 2)
self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth,
self.__thisHeight,
left, top))
self.__root.grid_rowconfigure(0, weight=1)
self.__root.grid_columnconfigure(0, weight=1)
self.__thisTextArea.grid(sticky=N + E + S + W)
#Call of the Bold function
self.__thisEditMenu.add_command(label="Gras",font=("arial", "12", "bold"),
command=self.__gras)
self.__root.config(menu=self.__thisMenuBar)
self.__thisScrollBar.pack(side=RIGHT, fill=Y)
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
file = open(self.__file, "r")
self.__thisTextArea.insert(1.0, file.read())
file.close()
#Bold function (the counter permit to generate a new tag name each time the function is called.
# The function check the counter number in order to decide if the text selection is in bold or normal font
# So the counter get +1 in one case an +2 in the other to differentiate them
def __gras(self):
sele=self.__thisTextArea.get(SEL_FIRST,SEL_LAST)
print (sele)
if self.__thisTextArea.tag_ranges('sel'):
if "colortag" + str(self.__countG -1) in self.__thisTextArea.tag_names(SEL_FIRST):
self.__thisTextArea.tag_add('colortag' + str(self.__countG), SEL_FIRST, SEL_LAST)
print ("le texte est gras")
self.__thisTextArea.tag_configure('colortag' + str(self.__countG),font=("arial", "12", "normal"))
self.__countG +=2
else:
self.__thisTextArea.tag_add('colortag' + str(self.__countG), SEL_FIRST, SEL_LAST)
print ('le texte est en normal')
self.__thisTextArea.tag_configure('colortag' + str(self.__countG), font=("arial", "12", "bold"))
self.__countG += 1
else:
pass
def __quitApplication(self):
self.__root.destroy()
#Save function that save the actual text in a .txt file
def __saveFile(self):
if self.__file == None:
self.__file = asksaveasfilename(initialfile='Untitled.txt',
defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents", "*.txt")])
if self.__file == "":
self.__file = None
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
self.__root.title(os.path.basename(self.__file) + " - Notepad")
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
def run(self):
self.__root.mainloop()
notepad = Notepad(width=600, height=400)
notepad.run()
'''
I recommend that you look into Pythons pickle functionality, there is no way to do what you want without saving the tags in a separate file or writing the tags into the file itself.

How do I solve TypeError: can only concatenate str (not "int") to str

I am writing a program in python for my personal use. But I have hit a wall here. Whenever I click the download button, it throws in this error:
`Exception in Tkinter callback
Traceback (most recent call last):
return self.func(*args)
File "f:\OG\Python\InstaDownloader.py", line 28, in Download
if(TheChoice == choiceCB[0]):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1652, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str`
This is my code for the program:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import instaloader
from instaloader import Post
instance = instaloader.Instaloader()
root = Tk()
root.title("Insta Downloader")
root.geometry("275x400") # set window
root.columnconfigure(0,weight=1) # set all content in middle
def Location():
global Folder_Name
Folder_Name = filedialog.askdirectory()
if(len(Folder_Name) > 1):
DebugLabel.config(text=Folder_Name,fg="green")
else:
DebugLabel.config(text="Please Choose Folder!",fg="red")
def Login():
instance.login(user=unLabel.get(),passwd=pwLabel.get())
DebugLabel.config(text="Logged in Successfully!",fg="green")
def Download():
TheChoice = choiceCB.get()
if(TheChoice == choiceCB[0]):
instance.download_saved_posts(target = Folder_Name)
DebugLabel.config(text="Downloaded all of the saved posts successfully!",fg="green")
elif(TheChoice == choiceCB[1]):
instance.download_profile(profile_name=singlePoint.get(), target = Folder_Name)
DebugLabel.config(text="Downloaded all of the posts successfully!",fg="green")
elif(TheChoice == choiceCB[2]):
post = Post.from_shortcode(instance.context, singlePoint.get())
instance.download_post(post,target = Folder_Name)
DebugLabel.config(text="Downloaded the post successfully!",fg="green")
NameLabel = Label(root,text="Insta Downloader",fg="red",font=("jost",20,"bold"))
NameLabel.grid()
SpacingA = Label(root, text="User Name", fg="black",font=("bold"))
SpacingA.grid()
unLabel = Entry(root,fg="black",font=("jost",10))
unLabel.grid()
SpacingB = Label(root, text="Pass Word", fg="black",font=("bold"))
SpacingB.grid()
pwLabel = Entry(root,fg="black",font=("jost",10))
pwLabel.grid()
SpacingC = Label(root, text="")
SpacingC.grid()
loginButton = Button(root,width=10,bg="red",fg="white",text="Login",font=("jost",10,"bold"),command=Login)
loginButton.grid()
SpacingD = Label(root, text="What do you want to download today ?")
SpacingD.grid()
wtd_Choice = ["Saved", "Profile", "Single"]
choiceCB = ttk.Combobox(root,values=wtd_Choice)
choiceCB.grid()
SpacingE = Label(root, text="Enter the profile or short-code here")
SpacingE.grid()
singlePoint = Entry(root,fg="black",font=("jost",10))
singlePoint.grid()
SpacingF = Label(root, text="")
SpacingF.grid()
pathButton = Button(root,width=10,bg="red",fg="white",text="Choose Path",font=("jost",10,"bold"),command=Location)
pathButton.grid()
SpacingG = Label(root, text="")
SpacingG.grid()
downloadButton = Button(root,width=10,bg="red",fg="white",text="Download",font=("jost",10,"bold"),command=Download)
downloadButton.grid()
SpacingH = Label(root, text="")
SpacingH.grid()
DebugLabel = Label(root,text="Debug Log",fg="blue",font=("jost",10))
DebugLabel.grid()
root.mainloop()
I'm guessing the problem is with line 27, 32 and 36. I have used the same type of code for other program and it worked correcttly.
You need to first convert number to string inorder to add it with string.
print("Hello World" + str(number))
Hope that helped you.

Return a user event function value as a string in Python before the code is compiled

I have a drag and drop GUI function that displays the filename and gives the file pathway. I am trying to plug that file path into Pandas to manipulate later down the road. My issue is that python trys to open the path way before the user can drop the file into the function. How do I tell it to wait until the user enters the data before it compiles. Below is the code that I am using and have narrowed it down to what I think is the problem. Bonus points if you can tell me how to turn the function into a class so that I dont have to edit the function per entry box.
import pandas as pd
import numpy as np
import docx
import os
import zipfile
import re
import PyPDF2
from docx2pdf import convert
import csv
from math import *
from pathlib import Path
import statistics
import matplotlib.pyplot as plt
from scipy.stats import linregress, stats
from tkinter import *
from tkinterdnd2 import *
from docx2pdf import convert
root = TkinterDnD.Tk()
root.title('Pathfinder')
root.geometry('600x400')
root.config(bg='#039dfc')
def drop(event):
var.set(event.data)
stringvar = str(event.data)
size = len(stringvar)
res = [] # list of file paths
name = ""
idx = 0
while idx < size:
if stringvar[idx] == "{":
j = idx + 1
while stringvar[j] != "}":
name += stringvar[j]
j += 1
res.append(name)
name = ""
idx = j
elif stringvar[idx] == " " and name != "":
res.append(name)
name = ""
elif stringvar[idx] != " ":
name += stringvar[idx]
idx += 1
if name != "":
res.append(name)
file_paths = res
current_e_box_item = set(e_box.get())
for file_path in file_paths:
if file_path.endswith(".XLS"):
path_object = Path(file_path)
file_name = path_object.name
if file_name not in current_e_box_item:
e_box.insert("end", file_name)
e_box.delete(0,last=size)
print(file_name)
print (res)
print(file_path)
print(path_object)
print(stringvar)
return file_path # this is what i want
var = StringVar()
e_box = Entry(root, textvar=var)
e_box.place(x=150, y=90, width=180, height=25)
e_box.drop_target_register(DND_FILES)
e_box.dnd_bind('<<Drop>>', drop)
File_as_DF = pd.read_excel(file_path) # This is where it needs to go
def drop2(event):
var2.set(event.data)
stringvar2 = str(event.data)
print (stringvar2)
var2 = StringVar()
e_box2 = Entry(root, textvar=var2)
e_box2.place(x=150, y=150, width=180, height=25)
e_box2.drop_target_register(DND_FILES)
e_box2.dnd_bind('<<Drop>>', drop2)
def drop3(event):
var3.set(event.data)
stringvar3 = str(event.data)
print(stringvar3)
var3 = StringVar()
e_box3 = Entry(root, textvar=var3)
e_box3.place(x=150, y=200, width=180, height=25)
e_box3.drop_target_register(DND_FILES)
e_box3.dnd_bind('<<Drop>>', drop3)
root.mainloop()
To answer the main question -- you need this:
File_as_DF = pd.read_excel(file_path) # This is where it needs to go
to happen after your drop(), not before it. Presumably you have a plan for what you want to do with that dataframe -- your drop() function should kick off a function that does that thing.
For the bonus points, instead of classes, I'd just have a function that builds a box along with its own drop function:
def drop2(event):
var2.set(event.data)
stringvar2 = str(event.data)
print (stringvar2)
var2 = StringVar()
e_box2 = Entry(root, textvar=var2)
e_box2.place(x=150, y=150, width=180, height=25)
e_box2.drop_target_register(DND_FILES)
e_box2.dnd_bind('<<Drop>>', drop2)
def drop3(event):
var3.set(event.data)
stringvar3 = str(event.data)
print(stringvar3)
var3 = StringVar()
e_box3 = Entry(root, textvar=var3)
e_box3.place(x=150, y=200, width=180, height=25)
e_box3.drop_target_register(DND_FILES)
e_box3.dnd_bind('<<Drop>>', drop3)
becomes:
def make_e_box():
var = StringVar()
def drop(event):
var.set(event.data)
print(event.data)
e_box = Entry(root, textvar=var)
e_box.drop_target_register(DND_FILES)
e_box.dnd_bind('<<Drop>>', drop)
return e_box
make_e_box().place(x=150, y=150, width=180, height=25)
make_e_box().place(x=150, y=200, width=180, height=25)

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'PY_VAR0'

import shutil,os
from tkinter import *
from tkinter import filedialog,font as tkfont, messagebox as m_box
import pickle
readFile = open("path.pkl","rb")
path_list = pickle.load(readFile)
win = Tk()
win.resizable(0, 0)
icon = PhotoImage(file="icon.png")
win.iconphoto(False,icon)
win.title("Backup Manager")
win.rowconfigure(0,weight=1)
win.columnconfigure(0,weight=1)
helv20 = tkfont.Font(family="Helvatica",size=20,weight=tkfont.BOLD)
#=================difine functions=================#
def add_path_win_func():
add_win = Toplevel()
add_win.focus_force()
add_win.title("Add More Paths")
add_win.iconbitmap(None)
lbl1= Label(add_win,text="Choose path To be Add in the list",font=("helvatica",15))
lbl2=Label(add_win,bg="dark grey",text="",font=("helvatica",14))
brws_btn = Button(add_win,command=lambda:browse(lbl2,add_win),text='Browse...',font=helv20)
add_btn = Button(add_win,command=lambda:add_func(add_win),text="Add",font=("helvatica",16))
Cancel_btn = Button(add_win,text="Cancel",command=lambda:add_win.destroy(),font=("helvatica",16))
lbl1.grid(row=0,column=0,padx=8,pady=8)
lbl2.grid(row=1,column=0,pady=8)
brws_btn.grid(row=1,column=1,pady=8)
add_btn.grid(row=2,column=0,pady=18,padx=18)
Cancel_btn.grid(row=2,column=1,pady=18,padx=18)
add_win.mainloop()
def add_func(zz):
global path_list,choosed_path,path_lst_box
if choosed_path=="":
m_box.showerror("please choose a path")
else:
write_file = open("path.pkl","wb")
path_list.append(choosed_path)
pickle.dump(path_list,write_file)
write_file.close()
path_lst_box.delete(0)
path_lst_box.insert(END,*path_list)
zz.destroy()
choosed_path = ""
def browse(lbl,zz):
global choosed_path
choosed_path = filedialog.askdirectory()
zz.focus_force()
lbl.config(text=choosed_path)
def backup_func():
global src_choosed,dest_choosed
src_choosed = str(src_choosed)
dest_choosed = str(dest_choosed)
folder = os.path.basename(src_choosed)
new_dest = str(f"{dest_choosed}/{folder}")
if not os.path.exists(new_dest):
shutil.rmtree(new_dest)
else:
None
shutil.copytree(src_choosed,dest_choosed)
#=================Backup Screen====================#
backup_screen = Frame(win,bg="#AFE1AF")
src_choosed = StringVar()
bl1 = Label(backup_screen,font=("verdana",20),text="Choose Source To Be Copied")
src_combo = OptionMenu(backup_screen,src_choosed,*path_list)
src_combo.config(font=helv20)
menu_src = win.nametowidget(src_combo.menuname)
menu_src.config(font=helv20)
dest_choosed = StringVar()
try:
dest_choosed.set(path_list[0])
src_choosed.set(path_list[0])
except:
None
bl2 = Label(backup_screen,font=("verdana",20),text="Choose Destination")
dest_combo = OptionMenu(backup_screen,dest_choosed,*path_list)
dest_combo.config(font=helv20)
menu_dest = win.nametowidget(dest_combo.menuname)
menu_dest.config(font=helv20)
backup_btn = Button(backup_screen,command=backup_func,text="Back up",width=20,font=("Verdana",15))
path_btn = Button(backup_screen,text="Manage Paths",width=20,
font=("Verdana",15),command=lambda:mng_path_screen.tkraise())
bl1.grid(row=0,column=0,pady=4)
src_combo.grid(row=1,column=0,sticky="ew",pady=4)
bl2.grid(row=2,column=0,pady=4)
dest_combo.grid(row=3,column=0,sticky="ew",pady=4)
backup_btn.grid(row=4,column=0,pady=4)
path_btn.grid(row=5,column=0,pady=4)
#==================Manage Path==================#
mng_path_screen = Frame(win,bg="#E4D00A")
path_lst_box = Listbox(mng_path_screen,width=50)
path_lst_box.insert(0,*path_list)
add_path_btn = Button(mng_path_screen,text="Add Path",
command=add_path_win_func,font=("verdana",16))
go_back_btn = Button(mng_path_screen,text="Go Back",
command=lambda:backup_screen.tkraise(),font=("verdana",16))
path_lst_box.grid(row=0,column=0,padx=50, pady=6)
add_path_btn.grid(row=1,column=0)
go_back_btn.grid(row=2,column=0)
for frame in (backup_screen,mng_path_screen):
frame.grid(column=0,row=0,sticky="nswe")
backup_screen.tkraise()
win.mainloop()
i want to make a backup software for personal use but i am having this error when i am clicking on backup button.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "c:\Users\DELL\Documents\VS Code Insiders\BackUp Maker\bakup.py", line 70, in backup_func
shutil.copytree(src_choosed,dest_choosed)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 555, in copytree
with os.scandir(src) as itr:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'PY_VAR0
You have to add.get() to print the value of a stringvar. var is a reference to a Tkinter.StringVar object. You need to call its get method to access the value that it represents:
It should be:
shutil.copytree(src_choosed.get(),dest_choosed.get())
Replace it wherever such occurences are present

Categories