Using same dataframe name in multiple functions in python - python

I have two excel files to import; file1.xls and file2.xls. I have define two separate function to import and third function to merge these files. However, merge is not happening. The error is showing
NameError: Name 'File1' is not defined.
I am using below code. Please help.
from tkinter import messagebox, filedialog, Frame, Button, Tk, Menu
import pandas as pd
def importivl():
global File1
LI_Filepath = filedialog.askopenfilename()
File1 = pd.read_excel(LI_Filepath)
messagebox.showinfo("File1", "File Imported Successfully")
def importcatfile():
global File2
Cat_Filepath = filedialog.askopenfilename()
File2 = pd.read_excel(Cat_Filepath)
messagebox.showinfo("File2", "File Imported Successfully")
def mergeivlcat():
File1 = pd.merge(File1, File2, on = "ID", how = "left")
def phase_one():
frame = Frame(root)
frame.pack()
import_LI_File = Button(root, text = "Import File1", command = importivl).pack()
import_Category_File = Button(root, text = "Import File2", command = importcatfile).pack()
mergeivlcat()
root = Tk()
root.geometry("600x400")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Phase One", command = phase_one)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command = root.destroy)
menubar.add_cascade(label = "File", menu = filemenu)
root.config(menu = menubar)
root.mainloop()

Related

changing extensions of all images in a folder with tkinter

I want to convert the image formats of all images in a folder using tkinter. all extensions I want in a combobox but I don't know why this code doesn't work .no error is displayed.
from tkinter import filedialog, StringVar
from tkinter import ttk
root=tkinter.Tk()
root.geometry("800x600")
#defining functions
def get_folder():
global folder_path
folder_path = filedialog.askdirectory(initialdir='./', title="Select Folder")
print(folder_path)
def get_extension():
change_to = com.get()
change_from = "py"
files=os.listdir(folder_path)
for file in files:
if (".%s"%change_from) in file:
newfile=file.replace((".%s"%change_from),".%s"%change_to)
os.rename((folder_path+'/'+file),(folder_path+'/'+newfile))
#defining widgets for frames
folder_label = tkinter.Label(from_frame)
browse_button = tkinter.Button(from_frame, text="Browse", command=get_folder)
change_button = tkinter.Button(button_frame, text="Change Extension", command=get_extension)
change_button.pack()
#defining combobox
com = StringVar()
list_combo = ['.png','.jpg','.jpeg', '.svg', '.tif','.bmp','.gif','ppm']
combox = ttk.Combobox(root, width = 25, font = 'arial 19 bold', value = list_combo, state = 'r', textvariable = com)
combox.place(x= 190, y= 190)
combox.set('select type')
root.configure(bg = 'coral1')
root.mainloop()```
Is this what You want:
from tkinter import Tk, Button, Label, StringVar, Frame
from tkinter.ttk import Combobox
from tkinter.filedialog import askdirectory
import os
def convert_extensions():
path = dir_lbl.cget('text')
from_ = from_var.get()
to_ = to_var.get()
files_from = [f'{path}/{file}' for file in os.listdir(path) if file.split('.')[-1] == from_]
files_to = ['.'.join(file.split('.')[:-1]) + '.' + file.split('.')[-1].replace(from_, to_) for file in files_from]
for from_file, to_file in zip(files_from, files_to):
os.rename(from_file, to_file)
print(f'{"-" * 100}\n'
f'{"From:": <10} {from_file}\n'
f'{"To:": <10} {to_file}\n')
root = Tk()
root.geometry('500x200')
Button(root, text='Choose Directory', command=lambda: dir_lbl.config(text=askdirectory())).pack(pady=5)
dir_lbl = Label(root, text='')
dir_lbl.pack(pady=5)
options_frame = Frame(root)
options_frame.pack(pady=5)
from_var = StringVar(value='Convert from')
list_combo = ['png', 'jpg', 'jpeg', 'svg', 'tif', 'bmp', 'gif', 'ppm']
Combobox(options_frame, value=list_combo,
textvariable=from_var, state='r').pack(side='left', padx=5, pady=5)
to_var = StringVar(value='Convert to')
Combobox(options_frame, value=list_combo,
textvariable=to_var, state='r').pack(side='left', padx=5, pady=5)
Button(root, text='Convert', command=convert_extensions).pack(pady=5)
root.mainloop()
This however allows more control in that You can choose both the extension to convert and to which one convert.
This is pretty basic so if You have any questions, ask. I will probably add a detailed explanation later but for now this is all I can do. Oh and btw that three line print function is not necessary at all and it probably should be made to display that in tkinter window or sth but otherwise it can be removed.

NameError: name 'root' is not defined trying to click on menubar

I will try to be concrete, When I tried to click on the 'New' option menubar it is give me an error saying that the root it is not defined, any help why it is happening that?:
file.py", line 6, in newfile
root.filename = filedialog.askopenfilename(initialdir = "/Libraries/Document",title = "Select file",filetypes = (("lre
files",".lre"),("all files",".*"))) NameError: name 'root' is not
defined
I have two file in one I have this code file.py:
from tkinter import filedialog
from tkinter import *
def newfile():
print('hello')
root.filename = filedialog.askopenfilename(initialdir = "/Libraries/Document",title = "Select file",filetypes = (("lre files","*.lre"),("all files","*.*")))
print (root.filename)
And part of the other is this menu:
from tkinter import filedialog
from tkinter import *
import library.file as New
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
root = Tk()
root.state("zoomed")
root.title("Interactive Toys")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=New.newfile)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu = menubar)
root.mainloop()

I can't Manage to close from in Python 3 with tkinter

I am trying to build a xml parser in python, i start to build gui framework, and here i need to create some forms to save some settings values. I manage to make it work and save some values to txt files for startup. But what ever i tried i can't manage to close the settings form when i click button. i need to close it with the x on the window. i can't find the root of the issue.
what i am trying to do is, when i click Cancel, form will be closed. if i click Save, form will first save data then close.
thanks a lot for your supports.
my code is as follows:
try:
# for Python2
print ("Importing for py2");
from Tkinter import * ## notice capitalized T in Tkinter
import tkFileDialog
except ImportError:
# for Python3
print ("Importing for py2 Failed !!!!");
print ("Importing for py3");
from tkinter import *
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import messagebox
mainform = Tk()
mainform.minsize(300,100)
mainform.geometry('{}x{}'.format(800, 600))
mainform.title("OVF Template Parser - By Gurhan Cagin (R) 2018")
textPad = ScrolledText(mainform, width=100, height=80)
textPad.pack()
## functions and procdures
def donothing():
x = 0
def quit():
if messagebox.askokcancel("Quit", "Do you really want to quit?"):
exit()
def about_command():
label = messagebox.showinfo("About", "Nokia OVF Template Parser \nCopyright 2018 \nNo rights left to reserve")
def open_command():
file = filedialog.askopenfile(parent=mainform, mode='rb', title='Select a file')
if file != None:
contents = file.read()
textPad.insert('1.0',contents)
file.close()
def SettingsFormFxn():
settingsForm = Tk()
settingsForm.minsize(300,100)
settingsForm.geometry('{}x{}'.format(750, 550))
settingsForm.title("Settings for the devault values")
## Frames
top_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
bottom_frame = Frame(settingsForm, width = 740, height = 50, pady = 3)
settingsForm.grid_rowconfigure(1, weight=1)
settingsForm.grid_columnconfigure(0, weight=1)
top_frame.grid(row=0, sticky="ew")
bottom_frame.grid(row = 4, sticky = "e")
b1 = Label(top_frame, text = "CPU per Core in Ghz:")
b1.grid(row = 0, column = 0)
entryText = StringVar(settingsForm, "2.1")
e1 = Entry(top_frame, textvariable = entryText, width = 5)
e1.grid(row = 0, column = 2)
def SaveFxn():
with open("settings.txt", "w") as f:
f.write(e1.get() + "\n")
##f.write(ent2.get() + "\n")
def CancelFxn():
settingsForm.destroy
cancel = Button(bottom_frame, text = "Cancel", command = CancelFxn, pady = 10, padx = 10,activebackground='grey',activeforeground='#AB78F1',bg='#e87474',highlightcolor='red')
cancel.grid(row = 0, column = 10)
save = Button(bottom_frame, text = "Save", command = SaveFxn, pady = 10, padx = 10)
save.grid(row = 0, column = 11)
settingsForm.mainloop()
## EOF FXNS
## Menu Definitions
menubar = Menu(mainform)
## File Menu
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Open", command = open_command)
filemenu.add_separator()
filemenu.add_command(label="Exit", command = quit)
menubar.add_cascade(label="File", menu=filemenu)
## Settings Menu
settingsmenu = Menu(menubar, tearoff = 0)
settingsmenu.add_command(label = "Settings", command = SettingsFormFxn)
menubar.add_cascade(label="Settings",menu=settingsmenu)
## About Menu
aboutmenu = Menu(menubar, tearoff = 0)
aboutmenu.add_command(label = "About", command = about_command)
menubar.add_cascade(label="Help", menu=aboutmenu)
mainform.config(menu=menubar)
## EOF Menu Definitions
## Main loop
mainloop()
You forgot your parenthesis when trying to call settingsForm.destroy.
def CancelFxn():
settingsForm.destroy()

How to use class and self here to get two different entries?

With my current code, it does not matter whether I click on "Input Folder" - Change or "JukeBox" change the result always gets displayed in "JukeBox" entry. This is incorrect, using class and self how can I change the code to display result from "Input Folder" - Change in "Input Folder" entry and the result from "Jukbox" - Change in "Jukebox" entry?
Also, how can I save the selected folders to a file so that it is there on app exit and re open?
My code:
import os
from tkinter import *
from tkinter import filedialog
inPut_dir = ''
jukeBox_dir = ''
def inPut():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
inPut_dir = StringVar()
inPut_dir = os.path.abspath(opendir)
entry.delete(0, END)
entry.insert(0, inPut_dir)
def jukeBox():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='JukeBox')
jukeBox_dir = StringVar()
jukeBox_dir = os.path.abspath(opendir)
entry.delete(0, END)
entry.insert(0, jukeBox_dir)
root = Tk()
root.geometry("640x240")
root.title("Settings")
frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)
text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
text = Label(frametop, text="JukeBox").grid(row=6, column=2)
entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)
ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frametop, text="Change", command=jukeBox).grid(row=6, column=28)
ButtonC = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
ButtonD = Button(frameright, text="Cancel").grid(row=5, column=15)
frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)
root.mainloop()
See attached image:enter image description here
Your code has both:
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
and
entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)
with jukeBox_dir/row 6 overriding inPut_dir/row 5
Therefore, in def input:
where you have:
entry.insert(0, inPut_dir)
You'll get the result in row 5 (jukebox_dir)

menubar not defined in python

i am trying to make a program using the tkinter library in python but it gives error showing that ---
NameError: name 'menubar' is not defined
import tkinter
import sys
def hey():
print("hello")
def myNew():
mlabel = Label(root,text="yo").pack()
root = tkinter.Tk()
root.title("Wizelane")
root.geometry('400x80+350+340')
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="New",command=myNew)
label = tkinter.Label(root,text="say hello")
label.pack()
hello = tkinter.Button(root,text="hello",command=hey)
hello.pack()
root.mainloop()
You are missing some important parts here.
You need to configure the menu first and you also need to add the cascade label.
Take a look at this code.
import tkinter
def hey():
print("hello")
def myNew():
# you forgot to use tkinter.Label here.
mlabel = tkinter.Label(root, text="yo").pack()
root = tkinter.Tk()
root.title("Wizelane")
root.geometry('400x80+350+340')
my_menu = tkinter.Menu(root)
# configure root to use my_menu widget.
root.config(menu = my_menu)
# create a menu widget to place on the menubar
file_menu = tkinter.Menu(my_menu, tearoff=0)
# add the File cascade option for drop down use
my_menu.add_cascade(label = "File", menu = file_menu)
# then add the command you want to add as a File option.
file_menu.add_command(label="New", command = myNew)
label = tkinter.Label(root, text="say hello")
label.pack()
hello = tkinter.Button(root, text="hello", command = hey)
hello.pack()
root.mainloop()

Categories

Resources