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()
So I'm making a script for a raspberry pi 3-b. The idea is to take sensor readings from 4 sensors, and display each reading, updating over time, in each corner overtop of a background image. I am mostly unfamiliar with python, and new to tkinter.
The following is my current code.
from tkinter import *
from PIL import ImageTk
import Adafruit_DHT
import tkinter as tk
from tkinter import font as tkfont
window = Tk()
def main():
c = Canvas(window,height=480,width=800)
image = ImageTk.PhotoImage(file="/home/pi/Desktop/AppFiles/AppBackround.jpg")
c.create_image(0,0,image=image,anchor=NW)
text1 = tk.StringVar()
text2 = tk.StringVar()
text3 = tk.StringVar()
text4 = tk.StringVar()
myFont = tkfont.Font(family="Titillium Web", size=32)
c.create_text(10,10,text=text1,fill="yellow",font=myFont)
c.create_text(10,450,text=text2,fill="yellow",font=myFont)
c.create_text(750,10,text=text3,fill="yellow",font=myFont)
c.create_text(750,450,text=text4,fill="yellow",font=myFont)
c.pack()
def update():
sensor = Adafruit_DHT.DHT22
DHT22_pin1 = 4
DHT22_pin2 = 17
DHT22_pin3 = 27
DHT22_pin4 = 22
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
text="Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1)
text="Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2)
text="Temperature3={0:0.1f}*C Humidity3={1:0.1f}%".format(temperature3, humidity3)
text="Temperature4={0:0.1f}*C Humidity4={1:0.1f}%".format(temperature4, humidity4)
window.after(100, update)
main()
update()
window.mainloop()
For some reason, my image is displaying as a blank gray background and my text is not displaying the readings or updating. instead I get this
What am I doing wrong, can anyone please explain what is going wrong here and how I might fix it?
With advice from some of the comments, I produced this, It works well. Thanks guys
from tkinter import *
from PIL import ImageTk
import Adafruit_DHT
import tkinter as tk
from tkinter import font as tkfont
sensor = Adafruit_DHT.DHT22
DHT22_pin1 = 4
DHT22_pin2 = 17
DHT22_pin3 = 27
DHT22_pin4 = 22
window = Tk()
c = Canvas(window,height=480,width=800)
image = ImageTk.PhotoImage(file="/home/pi/Desktop/AppFiles/AppBackround.jpg")
c.create_image(0,0,image=image,anchor=NW)
myFont = tkfont.Font(family="Titillium Web", size=32)
textVar1 = tk.StringVar()
textVar2 = tk.StringVar()
textVar3 = tk.StringVar()
textVar4 = tk.StringVar()
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
textVar1.set("Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1))
textVar2.set("Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2))
textVar3.set("Temperature3={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature3, humidity3))
textVar4.set("Temperature4={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature4, humidity4))
text1 = c.create_text(10,10,text=textVar1.get(),fill="yellow",font=myFont)
text2 = c.create_text(10,450,text=textVar2.get(),fill="yellow",font=myFont)
text3 = c.create_text(750,10,text=textVar3.get(),fill="yellow",font=myFont)
text4 = c.create_text(750,450,text=textVar4.get(),fill="yellow",font=myFont)
c.pack()
def update():
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
textVar1.set("Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1))
textVar2.set("Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2))
textVar3.set("Temperature3={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature3, humidity3))
textVar4.set("Temperature4={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature4, humidity4))
c.itemconfigure(text1, text=textVar1.get())
c.itemconfigure(text2, text=textVar2.get())
c.itemconfigure(text3, text=textVar3.get())
c.itemconfigure(text4, text=textVar4.get())
window.after(100, update)
update()
window.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()
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.