Once the user imports a text file, it is then displayed on scrolledtext. Then it is encrypted using a translator and displayed on another scrolledtext like so:
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import *
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVZMNXPBDCRJTQEGHK'
letters += letters.lower()
encryption_code += encryption_code.lower()
enc = dict(zip(letters,encryption_code))
window = tkinter.Tk()
style = ttk.Style(window)
style.configure("BW.TLabel")
import_frame = tkinter.Frame(window)
def import_txt():
global import_list
file_name = askopenfilename(filetypes=[("Text files","*.txt")])
import_list = []
with open(file_name, 'r') as f:
import_list = f.readlines()
encrypttxt.pack()
f.close()
def encrypt_txt():
global letters
global encryption_code
global import_list
global translated
pre = "".join(import_list)
translated = "".join([i.translate(str.maketrans(letters, encryption_code)) for i in import_list])
display_txt.insert('insert', translated)
precrypt.insert('insert', pre)
display_txt.pack(side=RIGHT)
precrypt.pack(side=LEFT)
display_txt = tkinter.scrolledtext.ScrolledText(import_frame)
encrypttxt = ttk.Button(import_frame, text="Encrypt", command=encrypt_txt)
precrypt = tkinter.scrolledtext.ScrolledText(import_frame)
start = ttk.Button(window, text="START", command=import_txt)
start.pack()
import_frame.pack()
window.mainloop()
My problem is that the program hangs when a large file is imported and encrypted. The larger the file, the longer it hangs.
Related
Good day folks,
I created a simple GUI that let's the user browse through their files with tkinter's filedialog.
After picking one, python reads the data from the (excel) file, and with that creates a new .txt file.
Now after doing that, I would like python to make that .txt file pop up, so that the user gets to see the result.
How do I do this?
Edit for the bot-moderator- he wanted code examples:
File1.py
from contextlib import nullcontext
import File2 as tp
import tkinter as tk
from tkinter import StringVar, messagebox
from tkinter import filedialog
filename = None
def pickFile():
global filename
filename = filedialog.askopenfilename()
#Creating main window
master = tk.Tk()
masterWidth = 350
masterHeight = 250
master.iconbitmap('C:\...')#directory
master.title('Title')
# get the screen dimension
screen_width = master.winfo_screenwidth()
screen_height = master.winfo_screenheight()
# find the center point
center_x = int(screen_width/2 - masterWidth / 2)
center_y = int(screen_height/2 - masterHeight / 2)-100
# set the position of the window to the center of the screen
master.geometry(f'{masterWidth}x{masterHeight}+{center_x}+{center_y}')
#Creating startbutton
startButton = tk.Button (master, text="Start", height=1, width=3, command=lambda: tp.readFile(filename))
#Creating bladerknop
browseButton = tk.Button (master, text='browse...', command=pickFile)
browseLabel = tk.Label(master, text='Choose a file')
startButton.place(x=175,y=200)
browseButton.place(x=210,y=50)
browseLabel.place (x=110,y=52)
master.mainloop()
File2.py
import pandas as pd
import tkinter as tk
from tkinter import messagebox
#declaring variables for later use
data = None
def missingValues(path):
if path is not None:
data = pd.read_excel(path, header=None)
return data
else:
messagebox.showinfo('No file chosen', 'Choose a file first.')
def readFile(path):
data = missingValues(path)
with open("C:\...\newFile.txt", 'w') as newTxt:
count = 0
for index, row in data.iterrows():
code = data.loc[count,0]
price = toEightBits(data.loc[count,1])
newTxt.write(str(code))
newTxt.write(str(price))
newTxt.write("\n")
count += 1
newTxt.close()
from cgitb import text
from distutils.cmd import Command
import tkinter as tk
from socket import timeout
import time
import pyfirmata
import time
from time import sleep, strftime
from tkinter import Tk, Label
from tkinter import Tk, Label
import random
import os
import tkinter.font as tkFont
ports="COM4"
board = pyfirmata.Arduino('COM4')
analog_pin0 = board.get_pin('a:1:i')
x=0
it = pyfirmata.util.Iterator(board)
it.start()
pin=4
analog_pin0.enable_reporting()
board.digital[7].write(0)
voltage0 = ""
def main():
print("this is maoin")
def on():
global voltage0
root = tk.Tk()
root.geometry("600x500")
w = tk.Label(root, text="Hello, world!")
w.pack(pady=20)
# B = tk.Button(root, text ="Hello", command = main)
# B.pack()
w.config(text=voltage0)
w['text'] = "intial voltage"
B = tk.Button(root, text ="Hello", command = main)
B.pack()
root.mainloop()
def main ():
while True:
global voltage0
reading0 = analog_pin0.read()
if reading0 != None:
voltage0 = reading0 * 22.3
voltage0 = round(voltage0,2)
time.sleep(0.1)
print(voltage0)
w.config(text=voltage0)
w['text'] = voltage0
else:
voltage0 = float('nan')
string = strftime('%H:%M:%S %p')
if (voltage0>7.3):
time.sleep(0.1)
board.digital[pin].write(1)
board.digital[6].write(0)
if(voltage0<6.5):
time.sleep(0.1)
board.digital[pin].write(0)
board.digital[6].write(1)
if (voltage0==7.3):
print()
print(voltage0)
print(string)
w.config(text=voltage0)
w['text'] = voltage0
if (voltage0==6.5):
print()
print(voltage0)
print(string)
w.config(text=voltage0)
w['text'] = voltage0
main()
on()
I have a file dialog to open a file in tkinter. I am getting the file name using tkinter using askopenfile() as shown below. Now I want to be able to access the path to the file outside the file_opener() function.
from tkinter import *
from tkinter import filedialog as fd
base = Tk()
base.geometry('150x150')
def file_opener():
file = fd.askopenfile()
if file:
y = file.name
def file():
f = open(y,'r') #Here i want to use value of y from above function
x = Button(base, text='Select a .txt/.csv file', command=lambda: file_opener())
x.pack()
mainloop()
You need to use return to return values. Modified code:
from tkinter import *
from tkinter import filedialog as fd
base = Tk()
base.geometry('150x150')
def file_opener():
file = fd.askopenfile()
if file:
return file.name
def file():
f=open(file_opener(),'r') #Here i want to use value of y from above function
print(f.read())
x = Button(base, text ='Select a .txt/.csv file', command = lambda:file())
x.pack()
mainloop()
I am trying to write a GUI that can display the log file in real time (tail -f log). The new line from the log file can be printed out into the terminal, but it cannot be loaded into the text field (line #). Can any one tell me why it won't put back to the text field?
from Tkinter import *
import os, time
import tkFileDialog
class Controller(object):
def __init__(self, master):
""" Main interface:
master - the top level window
"""
self._master = master
frame1 = Frame(self._master)
label = Label(self._master, text="Select a Log File")
label.pack(side=TOP)
currentLogfile = StringVar(self._master)
LogfileList = [f for f in os.listdir('.') if os.path.isfile(f)]
currentLogfile.set(LogfileList[0])
chooseLog = OptionMenu(self._master, currentLogfile, *LogfileList, command = self.file_open)
chooseLog.config(width = "300")
chooseLog.pack(side=TOP)
self._master.config(menu=chooseLog)
self._Text=Text(frame1, bg = 'black', fg = 'white')
self._Text.pack(side = TOP,fill=BOTH, expand = True,pady=20)
w = Scrollbar(self._Text)
w.pack(side=RIGHT, fill=Y)
frame1.pack(side=TOP, fill=BOTH, padx=5,expand=True)
def file_open(self,filename):
#clear text field
self._Text.delete('1.0', END)
with open(filename,'r') as f:
loglines = follow(f)
for line in loglines:
#print line
self._Text.insert(END,line)
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(5)
continue
yield line
if __name__ == "__main__":
root=Tk()
c=Controller(root)
root.title("log")
root.geometry("750x500")
root.mainloop()
I have some code which asks the user to import a file and then it will be encrypted using a translator. When I try this the program hangs a lot with large files or any files in general. I've tried to solve this using threading and a progressbar but I've sort of hit a dead end - I don't know how to update the progressbar which will correspond with the amount of time it will take to encrypt the file. This is what I have so far:
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import *
import threading
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVZMNXPBDCRJTQEGHK'
letters += letters.lower()
encryption_code += encryption_code.lower()
enc = dict(zip(letters,encryption_code))
window = tkinter.Tk()
style = ttk.Style(window)
style.configure("BW.TLabel")
import_frame = tkinter.Frame(window)
def import_txt():
global import_list
file_name = askopenfilename(filetypes=[("Text files","*.txt")])
import_list = []
with open(file_name, 'r') as f:
import_list = f.readlines()
progressbar.pack()
but1.pack()
encrypttxt.pack()
f.close()
def encrypt_txt():
global letters
global encryption_code
global import_list
global translated
progressbar.start()
pre = "".join(import_list)
translated = "".join([i.translate(str.maketrans(letters, encryption_code)) for i in import_list])
display_txt.insert('insert', translated)
precrypt.insert('insert', pre)
display_txt.pack(side=RIGHT)
precrypt.pack(side=LEFT)
def end():
if t.isAlive() == False:
progressbar.stop()
t.join()
toplevel = tkinter.Toplevel(window)
progressbar = ttk.Progressbar(toplevel, orient = HORIZONTAL, mode = "determinate")
t = threading.Thread(target=encrypt_txt)
but1 = ttk.Button(window, text= "Stop", command=end)
display_txt = tkinter.scrolledtext.ScrolledText(import_frame)
encrypttxt = ttk.Button(import_frame, text="Encrypt", command=encrypt_txt)
precrypt = tkinter.scrolledtext.ScrolledText(import_frame)
start = ttk.Button(window, text="Start", command=import_txt)
start.pack()
import_frame.pack()
window.mainloop()