Removing text files in Python tkinter - python

I have a problem, and I have no idea why it doesn't work!! :o
I want to remove text files via tkinter, so when the 'user' writes the text file's name and clicks on the button, it will be removed.
from tkinter import *
import tkinter.messagebox
import os, time
root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')
def remove():
if et in os.listdir():
os.remove(et)
tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
else:
tkinter.messagebox.showerror('Error!', 'File not found!')
label1 = Label(root, text = 'What to remove ?')
label1.place(x = 70, y = 140)
entry1 = Entry(root)
entry1.place(x = 180, y = 140)
#To fix extension bug
et = entry1.get()
if '.txt' not in et:
et += '.txt'
button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)
root.mainloop()

You were getting the value of et before the user had entered anything. Try this:
from tkinter import *
import tkinter.messagebox
import os, time
root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')
def remove():
#To fix extension bug
et = entry1.get()
if '.txt' not in et:
et += '.txt'
if et in os.listdir():
os.remove(et)
tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
else:
tkinter.messagebox.showerror('Error!', 'File not found!')
label1 = Label(root, text = 'What to remove ?')
label1.place(x = 70, y = 140)
entry1 = Entry(root)
entry1.place(x = 180, y = 140)
button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)
root.mainloop()

Here, check this out:
How to pass arguments to a Button command in Tkinter? (Edit: This is actually not so relevant to the question, but really useful knowledge with TkInter ;)
(In your code's remove function, "et" is not correctly set with the input field's content)
Actually, here's it fixed:
from tkinter import *
import tkinter.messagebox
import os, time
root = Tk()
root.geometry('450x320')
root.title('Remove a Text File')
label1 = Label(root, text = 'What to remove ?')
label1.place(x = 70, y = 140)
entry1 = Entry(root)
entry1.place(x = 180, y = 140)
def remove():
#To fix extension bug
et = entry1.get()
if '.txt' not in et:
et += '.txt'
print(os.listdir())
print(et)
if et in os.listdir():
print("os.remove(",et,")")
tkinter.messagebox.showinfo('Removed!', 'Successfully Removed!')
else:
tkinter.messagebox.showerror('Error!', 'File not found!')
button1 = Button(root, text = 'Remove', command = remove)
button1.place(x = 210, y = 200)
root.mainloop()

Related

How to delete text from Tkinter?

I want to know how do u delete text inside the Tkinter. The text is circled in red.
My code is as below:
from tkinter import *
from tkinter.ttk import Combobox
import win32com.client
root = Tk()
root.title('PM1 Digital Checklist')
root.geometry("400x400")
def open_excel():
if combo.get() == 'PPM8001':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8001.xlsx")
if combo.get() == 'PPM8002':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8002.xlsx")
if combo.get() == 'PPM8003':
myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
myLabel = Label(root, text=combo.get()).pack()
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
file = excel.Workbooks.Open(r"/path/to/PPM8003.xlsx")
options = ['PPM8001','PPM8002','PPM8003']
v = list(options)
combo = Combobox(root, values = v, width =40)
combo.set("Select which Prime Mover number")
combo.pack()
button = Button(root, text = "Select", command = open_excel).pack()
root.mainloop()
The image is here:
There are 2 things to fix:
use
myLabel = Label(root, text="Prime Mover Number Selected is:")
myLabel.pack()
To actually put a Label instance into a variable
use
myLabel.destroy()
To get rid of it.
Hope that's helpful!

Python text box

I am trying to take input name, email and password from user and print it in screen. But the variable is took is showing none every time. Can anyone solve my problem?
import tkinter as tk
import tkinter.font as f
r = tk.Tk()
name=''
email=''
password=''
def Print():
print("Name is",name)
print("Email is",email)
print("Password is",password)
f=tk.Frame(r,height=600,width=900)
f.pack()
name = tk.Label(f, text = "Name").place(x = 30,y = 50)
email = tk.Label(f, text = "Email").place(x = 30, y = 90)
password = tk.Label(f, text = "Password").place(x = 30, y = 130)
sbmitbtn = tk.Button(f, text = "Submit",activebackground = "pink", activeforeground = "blue",command=lambda:[Print(),f.destroy()]).place(x = 30, y = 170)
e1 = tk.Entry(f,textvariable=name).place(x = 80, y = 50)
e2 = tk.Entry(f,textvariable=email).place(x = 80, y = 90)
e3 = tk.Entry(f,textvariable=password).place(x = 95, y = 130)
r.mainloop()
you can use StringVar to get the string. the textvariable in your Label needs to be a Tkinter variable, quote:
"
textvariable= Associates a Tkinter variable (usually a StringVar) to
the contents of the entry field. (textVariable/Variable)
you can read more here
import tkinter as tk
import tkinter.font as f
r = tk.Tk()
name = tk.StringVar()
email = tk.StringVar()
password = tk.StringVar()
def Print():
print("Name is", name.get())
print("Email is", email.get())
print("Password is", password.get())
f = tk.Frame(r, height=600, width=900)
f.pack()
tk.Label(f, text="Name").place(x=30, y=50)
tk.Label(f, text="Email").place(x=30, y=90)
tk.Label(f, text="Password").place(x=30, y=130)
sbmitbtn = tk.Button(f, text="Submit", activebackground="pink", activeforeground="blue",
command=lambda: [Print(), f.destroy()]).place(x=30, y=170)
e1 = tk.Entry(f, textvariable=name).place(x=80, y=50)
e2 = tk.Entry(f, textvariable=email).place(x=80, y=90)
e3 = tk.Entry(f, textvariable=password).place(x=95, y=130)
r.mainloop()

How do I add a function result string on the tkinter window?

I am new in python and trying to make a program for converting a given string into a secret code. The string entered by user in the text box is taken as input and converted in secret code (using the encryption module). How do I display the result in the window (I tried using the label but it shows an error.)
from tkinter import *
import encryption as En # Loading Custom libraries
import decryption as De
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_box = None
resut_l = None
result_2 = None
def b1_action(): # Encryption button
input_text = text_box.get()
if input_text == "":
print("Text field empty")
else:
En.enc_text(input_text) # Message is returned as 'code'
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
De.dec_text(input_text)
def enc_button(): # Button for rendering encryption
b1 = Button(root, text = "ENCRYPT", font = button1_font, command = b1_action)
b1.configure(bg = 'palegreen3', width = '10', height = '3')
b1.place(x = '120', y = '130')
def dec_button(): # Button for decryption
b2 = Button(root, text = "DECRYPT", font = button2_font, command = b2_action)
b2.configure(bg = 'palegreen3', width = '10', height = '3')
b2.place(x = '340', y = '130')
def main(): #This is the core of GUI
global root
global text_box
root = Tk()
root.geometry("550x350")
root.configure(bg = "MediumPurple1")
win_text = Label(root, text = 'Enter text below and Choose an action:', bg = 'MediumPurple1', font = font_L1)
win_text.place(x = '10', y = '50')
text_box = Entry(root, text = 'Enter the Text', width = 60, bg = 'light blue')
text_box.place(x = '100', y = '100')
inst_text = Label(root, text = instructions, bg = "MediumPurple1", font = font_inst)
inst_text.pack(side = BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
And here is the encryption module
def enc_text(line):
msg = str(line).replace(' ', '_').lower()
msg_list = list(msg)
all_char = list("abcdefghijklmnopqrstuvwxyzabc_!?#")
for i in range(0, len(msg)):
pos_replaced = all_char.index(str(msg_list[i])) #will give the positon of the word to be replaced in the main list of alphabets
msg_list.insert(i, all_char[pos_replaced + 3]) #will replace the elements one by one
msg_list.pop(i + 1)
i += 1
code = ''.join(msg_list).replace('#', ' ')
print(code)
You can also suggest some improvisations.
Part of the problem is that Entry widgets don't have a text= configuration option, so it's completely ignored in the line:
text_box = Entry(root, text='Enter the Text', width=60, bg='light blue')
The best way to handle the character contents of an Entry is by using its textvariable= option and setting the value of it to be an instance of a tkinter.StringVar, then the getting and setting the value of that object will automatically update the Entry widget on the screen.
Below is your code with changes made to it to do this. Note I commented and changed a few unrelated things to be able to run the code, but tried to indicate the most important ones. Also note I added a return code statement at the very end of the enc_text() function in your custom encryption module.
from tkinter import *
import encryption as En # Loading Custom libraries
#import decryption as De # DON'T HAVE THIS.
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_var = None # ADDED.
text_box = None
resut_l = None
result_2 = None
# CHANGED TO USE NEW "text_var" variable.
def b1_action(): # Encryption button
input_text = text_var.get()
if input_text == "":
print("Text field empty")
else:
text_var.set(En.enc_text(input_text))
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
"""De.dec_text(input_text)"""
def enc_button(): # Button for rendering encryption
b1 = Button(root, text="ENCRYPT", font=button1_font, command=b1_action)
b1.configure(bg='palegreen3', width='10', height='3')
b1.place(x='120', y='130')
def dec_button(): # Button for decryption
b2 = Button(root, text="DECRYPT", font=button2_font, command=b2_action)
b2.configure(bg='palegreen3', width='10', height='3')
b2.place(x='340', y='130')
def main(): #This is the core of GUI
global root
global text_box
global text_var # ADDED
root = Tk()
root.geometry("550x350")
root.configure(bg="MediumPurple1")
win_text = Label(root, text='Enter text below and Choose an action:',
bg='MediumPurple1', font=font_L1)
win_text.place(x='10', y='50')
text_var = StringVar() # ADDED
text_var.set('Enter the Text') # ADDED
# CHANGED text='Enter the Text' to textvariable=text_var
text_box = Entry(root, textvariable=text_var, width=60, bg='light blue')
text_box.place(x='100', y='100')
inst_text = Label(root, text="instructions", bg="MediumPurple1",
font=font_inst)
inst_text.pack(side=BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()

finding & returning specific line from files in python with tkinter

i am a newbie in python, and i am trying to code a comparison tool and i used tkinter in python 2.7. my gui seems to work fine, but i cannot find the line containing the 'key' to return (even if i use correct key). hoping for your help.
import Tkinter as tk
from Tkinter import *
import os
import tkFont
result = ""
key = ""
def clear():
var4.set("Results...")
entry.set("")
def process():
key = entered.get()
if len(key) == 5 or len(key) == 6:
result = look_up()
var4.set(result)
else:
result = 'Invalid Entry, please enter 5-6 alphanumeric characters... !'
var4.set(result)
def look_up():
file = "compared.txt"
fh = open(file, 'r')
key = pdbCode.get()
lines = fh.readlines()
for line in lines:
#just trying to return a single line first to check
if line.strip().startswith(key):
#a, b, c, d = line.split("::")
#print "For item : " + str(a)
#print "description1 : " + str(b)
#print "description2 : " + str(c)
#print "value : " + str(c)
return line
else:
return "Code not in file..."
root = Tk()
root.title('Comparisson')
root.geometry('550x550+200+200')
entry = StringVar()
entered = Entry(root,textvariable = entry, width = 15)
entered.pack()
button1 = Button(root, text='COMPARE', width = 10, pady = 5, command = process)
button1.pack()
var4 = StringVar()
label4 = Label( root, textvariable=var4, pady = 45)
var4.set("Result here...")
label4.pack()
button2 = Button(root, text='CLEAR ALL', width = 10, command = clear)
button2.pack()
button3 = Button(root, text='QUIT', width = 10, command = root.destroy)
button3.pack()
root.resizable(0, 0)
root.mainloop()

How do I make a tkinter entry widget?

This is my code:
import random
from tkinter import *
root=Tk()
a=Canvas(root, width=1000, height=1000)
a.pack()
e = Entry(root)
paralist = []
x=random.randint(1,10)
file = open("groupproject.txt")
line = file.readline()
for line in file:
paralist.append(line.replace("\n", ""));
a.create_text(500,50, text = "Typing Fun", width = 700, font = "Verdana", fill = "purple")
a.create_text(500,300, text = paralist[x], width = 700, font = "Times", fill = "purple")
#master = Tk()
#a = Entry(master)
#a.pack()
#a.focus_set()
#def callback():
# print (a.get())
root.mainloop()
The commented section is supposed to print an entry widget underneath a paragraph but instead it gives an error IndexError: list index out of range for line a.create_text(500,300, text = paralist[x], width = 700, font = "Times", fill = "purple"). If I use e instead of a it works but opens the entry widget in a separate window.
I'm trying to make the tkinter entry widget appear in the same window as the text. Can someone please tell me how to do this?
First off,
paralist = []
The list is empty so a random word between 1 and 10 will be wrong since theres nothing in the list.
master = Tk() # since Tk() is already assigned to root this will make a new window
a = Entry(master) # a is already assigned to canvas
a.pack() # this is already declare under a=canvas
a.focus_set()
def callback():
print (a.get())
Edit:
I suspect that your file might be the problem. This code:
import random
from tkinter import *
root = Tk()
a = Canvas(root, width = 400, height = 400)
a.pack()
e = Entry(root)
e.pack()
paralist = []
x = random.randint(1,10)
file = open("teste.txt")
line = file.readline()
for line in file:
paralist.append(line.replace("\n", ""));
a.create_text(200,50, text = "Typing Fun", width = 700, font = "Verdana", fill = "purple")
a.create_text(200,300, text = paralist[x], width = 700, font = "Times", fill = "purple")
b = Entry(root)
b.pack()
b.focus_set()
def callback():
print (a.get())
root.mainloop()
With this as "teste.txt":
test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
test10
Works fine for me.
import tkinter
window = tkinter. Tk()
window.geometry('200x200')
ent= tkinter.Entry(window)
ent.pack()
This is the easiest way to do it in tkinter. If you need something else Just ask me:)

Categories