Error : Continue "Outside of Loop" in python - python-3.x

#Mark the continue statement. I want to bring the control to the beginning of the if-elif condition. so that if user chooses excel after choosing csv , without closing exiting from the window. The label gets updated accordingly on the "root" window. #
# importing tkinter and tkinter.ttk and all their functions and classes
import tkinter
import tkinter.ttk
import os
import sys
import time
# importing askopenfile function from class filedialog
from tkinter.filedialog import askopenfile
root = tkinter.Tk()
root.geometry('400x200')
root.title("CR7 - GSM BSC - Automation Tool ")
label = tkinter.Label(root, text ="Please Select the CR7 Input file for Generating Scripts").pack#(side="top", pady=10)
# This function will be used to open file in read mode and only excel & csv can be opened
def open_file():
file = askopenfile(mode='r', filetypes=[('CSV Files', '*.csv'),('Excel 2003', '*.xls'),('Excel 2007', '*.xlsx')])
filepathstring = str(file)
if filepathstring.find("xls") > 1 or filepathstring.find("xlsx") > 1 and filepathstring.find("csv") <1 :
label1 = tkinter.Label(root, text="Selected file is 'Excel' File & will be converted to 'CSV' file ").pack(side="top",pady=40)
continue
elif filepathstring.find("xls") < 1 or filepathstring.find("xlsx") < 1 and filepathstring.find("csv") > 1 :
label2 = tkinter.Label(root, text="Selected file is 'csv' File ").pack(side="top", pady=20)
continue
btn = tkinter.Button(root, command=lambda: open_file(), text='Open').pack(side="top", pady=10)
root.mainloop()

If I understand you correctly you want to update the first label. Your issue is that you are packing the widgets before creating the reference variable. The python run time environment first creates the widgets; executes the .pack() method; then assigns the variable the results of the .pack() method which is None. Once you have a working reference you can use the .configure() method to change the text value. I didn't run the code, so if there are any issues pleas leave a comment, so I can correct.
# importing tkinter and tkinter.ttk and all their functions and classes
import tkinter
import tkinter.ttk
import os
import sys
import time
# importing askopenfile function from class filedialog
from tkinter.filedialog import askopenfile
root = tkinter.Tk()
root.geometry('400x200')
root.title("CR7 - GSM BSC - Automation Tool ")
label = tkinter.Label(root, text ="Please Select the CR7 Input file for Generating Scripts")
label.pack(side="top", pady=10) # Packing the label before you create a reference creates a reference to the return value of .pack() method which is None
btn = tkinter.Button(root, command=open_file, text='Open') # you don't need to use lambda unless passing a variable
btn.pack(side="top", pady=10)
# This function will be used to open file in read mode and only excel & csv can be opened
def open_file():
file = askopenfile(mode='r', filetypes=[('CSV Files', '*.csv'),('Excel 2003', '*.xls'),('Excel 2007', '*.xlsx')])
filepathstring = str(file)
if filepathstring.find("xls") > 1 or filepathstring.find("xlsx") > 1 and filepathstring.find("csv") <1 :
label.configure(text="Selected file is 'Excel' File & will be converted to 'CSV' file ")
elif filepathstring.find("xls") < 1 or filepathstring.find("xlsx") < 1 and filepathstring.find("csv") > 1 :
label.configure(text="Selected file is 'csv' File ")
root.mainloop()

Related

NameError: name 'Acte_D ' is not defined

I am currently developing a program to try an xml file. However I encounter a problem that has been blocking me for a few days now and I can rack my brains my beginner level in python and my many research does not help me to get over it.
I first try to retrieve 1 element from my xml file. I can do it well only the graphics window that should normally display it does not generate and I have the following error message:
The error :
window.fenetre_text(Acte_D) NameError: name 'Acte_D' is not defined`
well my code is :
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
from xml.dom import minidom`
global file
global Acte_D
global element_A
global lines
class fenetreM(Tk):
#GUI
def __init__(self, master=None,*args, **kwargs):
Tk.__init__(self,master, *args, **kwargs)
self.menu_bar()
self.title("EssaiV1.0.1")
self.geometry("800x400")
self.minsize(380,140)
self.config(background='#F0F0F2')
#New_frame=Frame(fenetreM, bg='#abd7f4')`
def menu_bar(self):
menu_bar = Menu(self)
menu_file = Menu(menu_bar, tearoff=0)
menu_file.add_command(label="Open", underline=0, command=self.open_file)
menu_file.add_command(label="Affichage",underline=0,command=self.do_something)
menu_file.add_separator()
menu_file.add_command(label="Exit",underline=1,command=self.quit)
menu_bar.add_cascade(label="File",underline=0, menu=menu_file)
menu_help = Menu(menu_bar, tearoff=0)
menu_help.add_command(label="About", command=self.do_about)
menu_bar.add_cascade(label="Help",underline=0, menu=menu_help)
self.config(menu=menu_bar)
valid = False
return(valid)
def open_file(self):
types = [("All Files",".*")]
file = askopenfilename(title="File to open : ", filetypes=types)
print("Copy")
doc = minidom.parse(file)
print(doc.nodeName)
print(doc.firstChild.tagName)
Acte_D = doc.getElementsByTagName("ActeDescription")
print("\n")
element_A = (f" we have {Acte_D.length} element \n Version : ")
for i in Acte_D:
screen_1=(i.getAttribute("version"))
print(screen_1)
print("\n")
return (Acte_D)
def fenetre_text(self,Acte_D):
tk=Text(fenetreM, height = 10, width =100)
Fenetre_A=tk.inset(END,textvariable=self.element_A+Acte_D)
Fenetre_A.pack(side="top", fill="x", expand=True)
return(Acte_D)
window = fenetreM()
window.fenetre_text(Acte_D)
window.mainloop()
Can someone explain my mistake to me?
Thanks
I tried to graphically display the result of Acte_D in my window defined in my method fenetre_text.
But I can't.

Filedialog creating blank lines when opening file explorer

I noticed using filedialog.askdirectory() creates two blank lines when it opens file explorer (see picture below). I've been looking into this for weeks and I can't figure out why this is happening. Is there a way to prevent these blank lines from being created?
#!/usr/bin/python3
import tkinter
from tkinter import filedialog
export_file_path = ""
#Export path for output file
def export_path():
global export_file_path
print("Before askdirectory() is called")
is_empty = filedialog.askdirectory()
print("After askdirectory() is called")
if is_empty != '':
export_file_path = is_empty.replace('/', '\\')
export_path()
print(export_file_path)
input('PAUSE')

Python3, difficulty with classes and tkinter

First of all to kick it off,
I'm not great at programming,
I have difficulty with understanding most basics,
I always try doing my uterly best to solve things like this myself.
I'm trying to create a simple gui that makes json files. Everything works fine. Fine in the sense that I'm able to create the files.
Now I wanted to get my code cleaned up and to the next level. I have added tabs to the tkinter screen and that is where the troubles starts. Because when I'm, on a differend tab, the function doesn't get the current selected items, so I added buttons to save that list and then move to different tab.
I have a function(Save_List_t), which looks at the selected items from the listbox(a_lsb1) and saves them to a list(choice_list_t). This function runs when I press button(a_button).
After doing that I got a problem, I don't want to use "global" but I need the list in a other function(Mitre_Gen_Techs) to generate the files. This function runs when I press a button on the third tab.(c.button1)
To tackel this problem, I saw a post where someone uses a class to fix it. However even after reading to the documentation about classes I still don't truely get it.
Now I'm stuck and get the error. Which I don't find that strange, it makes sense to me why it gives the error but what am I doing wrong or how do I solve this issue.
The error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\thans\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
TypeError: Save_List_t() missing 1 required positional argument: 'self'
The code I wrote:
from tkinter import *
from attackcti import attack_client
from mitretemplategen import *
from tkinter import ttk
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mitre ATT&Ck
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
ac = attack_client()
groups = ac.get_groups()
groups = ac.remove_revoked(groups)
techs = ac.get_enterprise_techniques()
techs = ac.remove_revoked(techs)
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Tkinter screen setup
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
root = Tk()
root.title("Mitre Att&ck")
root.minsize(900, 800)
root.wm_iconbitmap('')
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Functions / classes
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class Screen(object):
def __init__(self):
self.choice_list_t = []
self.choice_list_g = []
def Save_List_t(self):
for item in a_lsb2.curselection():
self.choice_list_t.append(a_lsb2.get(item))
print(self.choice_list_t)
def Save_List_g(self):
choice_list_g = []
for item in b_lsb1.curselection():
self.choice_list_g.append(b_lsb1.get(item))
print(self.choice_list_g)
def Mitre_Gen_Techs(self):
# Gen the json file
# mitre_gen_techs(self.choice_list_t, techs)
#testing class
print(self.choice_list_t)
def Mitre_Gen_Groups(self):
# Gen the json file
# mitre_gen_groups(self.choice_list_g, groups)
#testing class
print(self.choice_list_g)
def main():
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# First Tkinter tab
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
rows = 0
while rows < 50:
root.rowconfigure(rows, weight=1)
root.columnconfigure(rows, weight=1)
rows += 1
# Notebook creating tabs
nb = ttk.Notebook(root)
nb.grid(row=1, column=0, columnspan=50, rowspan=50, sticky='NESW')
# Create the differend tabs on the notebook
tab_one = Frame(nb)
nb.add(tab_one, text='APG')
tab_two = Frame(nb)
nb.add(tab_two, text='Actors')
tab_gen = Frame(nb)
nb.add(tab_gen, text='test')
# =-=- First Tab -=-=
# List box 1
a_lsb1 = Listbox(tab_one, height=30, width=30, selectmode=MULTIPLE)
# List with techs
a_lsb2 = Listbox(tab_one, height=30, width=30, selectmode=MULTIPLE)
for t in techs:
a_lsb2.insert(END, t['name'])
# Save list, to later use in Screen.Mitre_Gen_Techs
a_button = Button(tab_one, text="Save selected", command=Screen.Save_List_t)
# =-=- Second Tab -=-=
# List with TA's
b_lsb1 = Listbox(tab_two, height=30, width=30, selectmode=MULTIPLE)
for g in groups:
b_lsb1.insert(END, g['name'])
# Save list, to later use in Screen.Mitre_Gen_Groups
b_button = Button(tab_two, text="Save selected", command=Screen.Save_List_g)
# =-=- Third tab -=-=
c_button = Button(tab_gen, text="Print group json", command=Screen.Mitre_Gen_Groups)
c_button1 = Button(tab_gen, text="Print techs json", command=Screen.Mitre_Gen_Techs)
# Placing the items on the grid
a_lsb1.grid(row=1, column=1)
a_lsb2.grid(row=1, column=2)
b_lsb1.grid(row=1, column=1)
a_button.grid(row=2, column=1)
b_button.grid(row=2, column=1)
c_button.grid(row=2, column=1)
c_button1.grid(row=2, column=2)
root.mainloop()
# If main file then run: main()
if __name__ == "__main__":
main()
The application:
Image
I found someone who explained what was wrong.
Credits to Scriptman ( ^ , ^ ) /
simply adding:
sc = Screen()
And changing:
Button(tab_apg, text="Save selected", command=sc.Save_List_t)
Resolved the issue.

To do some operation with .docx by using python tkinter

I have created a script for getting the path name from user and do some .docx operations. When i run the script it is giving the total number of .docx in that folder but it doesn't work for the table counting. I don't know that I'm using correct code with tkinter. I have tried the pathlib and os.path but it doesn't work.
here is my code:
import os
import glob
import os.path
from docx import Document
from tkinter import *
def print_input():
#To print how many files with .docx extension in the folder
mypath = text_entry.get()
files=0
for name in os.listdir(mypath):
if name.endswith('.docx'):
files=files+1
print("Total No of Files:",files)
#To read the .docx and print how many tables in that
table=0
for name in glob.glob('/*.docx'):
doc=Document(name)
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="ID" :
table=table+1
print("Total Number of Tables: ", table)
root = Tk()
Label(root, text="Enter Path").grid(row=0)
text_entry = Entry(root)
text_entry.grid(row=1, column=0)
text_entry.config(background="yellow", foreground="blue")
Button(root, text='Submit', command=print_input).grid(row=3, column=0, sticky=W, pady=4)
mainloop()
When I try to specify the path name inside the glob it is working but when i try to pass the value from the textbox it is not executing instead of giving correct details it shows random numbers. Hope you understand my problem
Don't have any idea what "doesn't work" means, but you are getting names from "mypath"
for name in os.listdir(mypath):
but tables are coming from '/*.docx'
for name in glob.glob('/*.docx'):
Do it in one operation (and take a look at filedialog.askdirectory)
mypath = text_entry.get()
files=0
for name in os.listdir(mypath):
if name.endswith('.docx'):
files=files+1
#print("Total No of Files:",files)
#To read the .docx and print how many tables in that
table=0
##for name in glob.glob('/*.docx'):
doc=Document(name)
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="ID" :
table=table+1

how do you open two tkinter Windows one after the other.?

I am fairly new to python programming with its concept of class which is very different of languages like java, c++, c# ... and also the Tkinter library. I am trying to do something basic. First creating a frame that will allow the user to enter a string value; store that string value in memory then exit that frame. Creating a new file browser that will allow you to select a specific file then rename the chosen file with the string stored in memory earlier. I do not have any specific snippet of code to do that but I have two pieces of codes that could be combined to give me the result I want.
enter code here
# This is the snippet for the input user
def printtext():
global e
string = e.get()
return string
from Tkinter import *
root = Tk()
root.title('Name')
e = Entry(root)
e.pack()
e.focus_set()
b = Button(root,text='okay',command=printtext)
b.pack(side='bottom')
root.mainloop()
# This is for the file browser
import Tkinter,tkFileDialog
root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
Why don't you try with asksaveasfilename like in this example.But if you want to use file_path=askopenfilename with entry, than you would have to use OS library, with function os.rename (i think) .This code is written in python 3 so if you are using python2 than just change names of libraries.
from tkinter import *
import tkinter.filedialog as fd
def main():
root = Tk()
root.title('Name')
#e = Entry(root)
#e.pack()
#e.focus_set()
b = Button(root,text='okay',command= lambda:printtext(e))
b.pack(side='bottom')
root.mainloop()
def printtext(e):
#string = e.get()
#print(string)
file = fd.asksaveasfile(title='Choose a file')
#print(file)
main()

Resources