import pandas as pd
from tkinter import *
from tkinter import filedialog
def final():
Tk().withdraw() # Close the root window
in_path = filedialog.askopenfilename()
print(in_path)
df = pd.read_csv(in_path)
newList = df['delivery_price'].tolist()
print(newList)
output = list(map(lambda elem: float(elem.split()[0]), newList))
print()
print("Your total amount is: " + str(sum(output)))
button.destroy()
label = Label(root, text="Your total amount is \n" + str(sum(output)))
label.pack()
root = Tk()
button = Button(root, text="Find total", command=final)
button.pack()
button.place(relx=0.5,rely=0.5,anchor=CENTER)
root.title("Sherpa")
root.geometry('200x200+600+250')
root.mainloop()
I wrote this small program which extracts a specific column from a CSV file which the user chooses.
the column consists of text and float:
"AUD 31.33"
Then, it gets rid of the string, and save it as the only float in a list.
In the end, I get the total amount of the column.
I used TKinter for the gui:
when I run it in pyCharm:
1) a small window appears with a button "find total"
2) after clicking "find total", it ask for the .csv file
3) user chooses the file.
4) the total amount is displayed in the small window.
That's what I really wanted with the program. but now I want to make it .exe so that I don't have to open pycharm all the time.
I tried py2installer, it gets compiled but it doesn`t run. Is there any format to follow to make GUI apps that are executable.
Or do I have to make changes in my code?
Can you see what the error is that you get? (Sometimes difficult with exe-files, because the window closes after the error. I sometimes try to make a screenshot at the right moment).
I had a problem with the PyQt module when compiling a script with Tkinter using pyinstaller. What worked for me was the solution mentioned here. It's copying the qwindows.dll file to the directory \platforms\qwindows.dllin your pyinstaller output dir (..\dist\<your program.\platforms\qwindows.dll).
Related
I have created a GUI application with tkinter for data analysis. In the app I have several comboxes to list down the sheets of an uploaded excel file. The user can select a sheet name from the combox and the code will read the columns to process the data analysis.
Everything works in Python environment without producing an error. I converted the tkinter application by using both pyinstaller and auto-py-to-exe.
My problem is tkinter comboxes aren't functional in the .exe. They worked perfectly in the .py script but in .exe they are not even appearing after uploading. What could be the possible issue for this?
with pyinstaller I used the command:
pyinstaller --onefile --windowed name_of_script.py
and with Auto Py I browsed to my program and converted it.
this is how I created comboxes in .py
proboxATC = ttk.Combobox(self, textvariable=proATC_com, value=pathATC_sheets,state='readonly')
proboxATC.bind("<<ComboboxSelected>>",ATC_selected)
Here is a minimum working example. As you can see it works as a .py but the combox doesn't appear in the .exe.
import tkinter as tk
from tkinter import ttk
from tkmacosx import Button
import pandas as pd
root = tk.Tk()
root.geometry('400x400')
def OOE():
pathxl = tk.filedialog.askopenfilename(filetypes = [('Excel files', '*.xls*')], title = "Select an ATC file")
excel_file = pd.ExcelFile(pathxl)
sheet_names = excel_file.sheet_names
combo = tk.StringVar()
def selected(event):
print(box.get())
box = ttk.Combobox(root, textvariable=combo, value =sheet_names, state='readonly')
box.bind("<<ComboboxSelected>>",selected)
box.pack()
xl_btn = Button(root,text="ATC",foreground='#161327',background="#707087",command=lambda:OOE())
xl_btn.pack()
root.mainloop()
I was able to compile and run your program fine. I did have to add the following line to the imports at the top in order to get the filedialog to work, but I don't think this is necessary on all systems.
import tkinter.filedialog # added this line
And I also added openpyxl to the --hidden imports flag for pyinstaller.
pyinstaller -F -w --hidden-import openpyxl main.py
This is my first question.
I have a python program that recognize voice and reply with voice.
I wish to add a little GUI for my program (it should have only an image on background and a button to quit the program)
I would like that when I launch my code from terminal, it opened a Tkinter window and at the same time the python program start.
I’m working on Mac Os.
I use speech_recognition package to recognize voice and I use NSS speaker to let my computer speak.
This is a example of my code:
import speech_recognition as sr
from AppKit import NSSpeechSynthesizer
#VARIABLES
L = sr.Recognizer() #LISTENING
nssp = NSSpeechSynthesizer #SPEAKING
S = nssp.alloc().init()
while True:
audio = L.listen(source)
s = L.recognize_google(audio, language="en-US")
if s == "hi":
S.startSpeakingString_("Hello!!!")
Where do I have to write the Tkinter instructions to make sure that when I run my code it opens only a Tkinter window (while my program goes on) and not a shell's one?
You'll find it difficult to introduce your GUI as your code has already been written, note that everything in Tkinter has to be stored in some sort of Label or Widget and so you can't just print what you already have onto the Tkinter screen.
Here is some code to create a basic Tkinter window. Try searching online and playing around with how to present your variables within said window
import tkinter
from tkinter import *
root = tkinter.Tk()
root.configure(background = "#66ffdd") #here you can use any hex color code or just leave it blank and configure as default
root.title("Voice Program") #use the name of your program (this is the window header/title)
root.geometry("800x500") #these are your window dimensions
welcome = tkinter.Message(root, text = "Welcome to my program")
button = tkinter.Button(root, text="This button", command=print("hello")) #here insert a function for the button to perform i.e quit
welcome.pack()
button.pack() #packing presents your variables to the window - you can also use other geometry managers like grid
This site is really useful for showing you what widgets are available and what you can do with them - try searching any issues or posting a more specific question in the future if you struggle.
http://effbot.org/tkinterbook/button.htm
I'm running a script in a console to help me in a repetitive task.
I want open image in gallery and write down numbers from an image.
feh = subprocess.Popen(['feh', 'tmp.jpg'])
print ("Input number from image:")
number = input()
feh.kill()
This code works, but window managers keep focusing feh, which adds an additional step of refocusing console window. Is there an additional argument I can pass to prevent this behavior or another way around?
One dirty workaround is to simply refocus window by mouse.
I used xdotool
feh = subprocess.Popen(['feh', 'tmp.jpg'])
time.sleep(0.1)
subprocess.call(['xdotool', 'click', '1'])
something = input()
feh.kill()
Python has native GUI modules, named tkinter.
GUI program can be terrifyingly easy to write, if it is python.
#!/usr/bin/python2 -i
from Tkinter import *
from PIL import *
import os
files = [f for f in os.listdir('.') if f.endswith(".png")]
root = Tk()
label = Label(root)
label.pack()
for name in files:
im = PhotoImage(file=name)
label.config(image=im)
print("your number plz")
input_str = raw_input()
Im back again with another python issue.
A short while ago I wrote a console based program that pulls stats from a bitcoin miner on your local network. I've decided I'd like to turn it into a gui, and choose a combination of EasyGUI and Tkinter for my program.
My input boxes (ip, refresh rate,asic type) are all using EasyGUI, simply to save lines of code as Tkinter would take far more writing to accomplish the same. However, My actual results page is written using Tkinter as it allows me to refresh the displayed data at a user-defined interval.
My issue is this:
I had my program running happily, and then made some small ui tweaks (title, font, etc) and now after my most recent compile (using pyinstaller) I've noticed the stats (labels) don't update at all. I have looked over my code countless times now and cannot seem to find what is blocking the stats from changing at the defined intervals.
I am hoping someone with a fresh pair of eyes can help me find my stupid mistake, as it was running perfectly before these small additions.
Heres a cut-down version that still runs and produces the same issue:
import Tkinter as tk
from pycgminer import CgminerAPI
cgminer = CgminerAPI()
cgminer.host = 192.168.x.x
summary = cgminer.summary()
update = 1000
def L1(label):
def hashrate():
msg = "Your current GH/S = "
speed = msg , summary['SUMMARY'][0]['GHS 5s']
label.config(text=speed)
label.after(update, hashrate)
hashrate()
root = tk.Tk()
root.title("Eyes On Miner GUI V0.2")
label = tk.Label(root)
label.pack()
L1(label)
root.mainloop()
Full code on pastebin, in case you'd like to try to run it yourself. (python 2.7) Full Code
I ran this much of your code, substituting time() for the summary. It works in IDLE. From the console, either run with python -i program.py or add root.mainloop.
import tkinter as tk
from time import time
update = 1000
def L1(label):
def hashrate():
msg = "Your current GH/S = "
speed = msg , time()
label.config(text=speed)
label.after(update, hashrate)
hashrate()
root = tk.Tk()
root.title("Eyes On Miner GUI V0.2")
label = tk.Label(root)
label.pack()
L1(label)
If the problem is not with summary['SUMMARY'][0]['GHS 5s'], then there must be an incompatibility with either CgminerAPI or more likely with easygui. The latter is meant to replace tkinter, not be used together with it. If the code worked at first and then quit, then one of the additional functions you used must have triggered a conflict.
First time using Tkinter and I'm trying to make a widget that displays text from a text file and updates the widget when the text in the file changes. I can get a widget to read from a text file, but I can't seem to make it update when the text changes.
Here's the code I'm using right now:
from Tkinter import *
root = Tk()
root.minsize(740,400)
file = open("file location")
eins = StringVar()
data1 = Label(root, textvariable=eins)
data1.config(font=('times', 37))
data1.pack()
eins.set(file.readline())
root.mainloop()
I've searched for help on updating widgets but I can only find help with updating when a button is pressed or an entry widget is used. I was thinking of using a loop that goes through every minute, but wouldn't that just keep creating new widgets?
So you are only reading from file once in your example. As you suggest you need to add some kind of loop to enable you to reread the file often. The problem with normal loops in Tkinter is that they are run in the main thread, making your GUI unresponsive. To get around this, use the Tkinter's after method.
The after method schedules a function to be run after N milliseconds. For example:
from Tkinter import *
# This function will be run every N milliseconds
def get_text(root,val,name):
# try to open the file and set the value of val to its contents
try:
with open(name,"r") as f:
val.set(f.read())
except IOError as e:
print e
else:
# schedule the function to be run again after 1000 milliseconds
root.after(1000,lambda:get_text(root,val,name))
root = Tk()
root.minsize(740,400)
eins = StringVar()
data1 = Label(root, textvariable=eins)
data1.config(font=('times', 37))
data1.pack()
get_text(root,eins,"test.txt")
root.mainloop()
This will loop until the GUI is closed.