I have a scraping script of where im using tkinter for ui. When i build the exe(with pyinstaller) and open it it working well, But When i close it, it opens multiple instance of tkinter Window. I cant paste the full code. So i pasted all the tkinter code i am using.
Here is the Full code Github Gist here
import requests
from lxml import html
from tkinter import *
import tkinter as ttk
import re
import datetime
import os
from firebase import firebase
import hashlib
#import App as App
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
#Region Tk
root = Tk()
root['height'] = 400
root['width'] = 600
global firebase
firebase = firebase.FirebaseApplication('#######URL####',None)
f1 = Frame(root)
f1["height"] = root["height"]
f1["width"] = root["width"]
root.title("JD Scraper - Gear Up Studio ")
Label(f1,text = "Input Url : Example : https://www.justdial.com/Ahmedabad/Gyms ").grid(row=0,column = 0,)
def getBool(event):
print(boolvar.get())
#Check Button
global boolvar
boolvar = BooleanVar()
boolvar.set(False)
boolvar.trace('w', lambda *_: print("The value was changed"))
cb = Checkbutton(f1, text = "Tele Phone number", variable = boolvar)
cb.bind("<Button-1>", getBool)
cb.grid(row=1, column=1)
global key_filled
key_filled = Entry(f1,width=50)
key_filled.grid(row=2,column=0)
key_filled.focus_set()
global activate_button
activate_button = Button(f1 , text="Active Now")
activate_button.bind("<Button-1>",activate_key)
activate_button.grid(row=2, column=1)
result = Label(f1, width=50)
result.grid(row=1,column=2)
global submit_button
submit_button = Button(f1 , text="Scrape Now")
submit_button.bind("<Button-1>",button_clicked)
submit_button.grid(row=1, column=0)
submit_button.config(state=NORMAL)
key_validation()
f1.pack()
root.mainloop()
Demo Video here
i was facing the exact the same problem with firebase and pyqt5. After many tries i examine the firebase library. In init there is close_process_pool() function which is called when program exits and close all the multiprocessing pools. In tkinter and pyqt case we dont need this function as all the process is the childs of main GUI thread so simple removing that function resolves the problem.
Change the init file to this will resolve the issue.
import atexit
#from .async import process_pool
from firebase import *
'''
#atexit.register
def close_process_pool():
"""
Clean up function that closes and terminates the process pool
defined in the ``async`` file.
"""
process_pool.close()
process_pool.join()
process_pool.terminate()
'''
I can see cmd window pops when run your exe to remove that use this command -w and also to compile as onefile into dist folder use -F to compile it as a single file, do this to resolve the issue
pyinstaller -w -F replace this with your script name.py
It will compile the file as one file for you and the use will be res
Related
I am trying to open a exe file from C drive by clicking a button from my GUI and up till now i am unable to select the specific file. Can i know if there is any function to directly open the file in Tkinter. Currently,tkFileDialog.askdirectory only direct me to the FILES.
import Tkinter
import tkMessageBox
import tkFileDialog
import os
import subprocess
top = Tkinter.Tk()
def run():
File = tkFileDialog.askdirectory()
os.system(File)
b = Tkinter.Button(top, text = 'DAQoutput', command= run)
b.pack()
top.mainloop()
Directly using Tkinter? No there is no command for it but you don't need one. Tkinter is a GUI toolkit and that's all it does.
Instead use os.system() to launch your exe.
Your script should look something like this:
import Tkinter
import tkMessageBox
import tkFileDialog
import os
top = Tkinter.Tk()
def run(self):
File = tkFileDialog.askdirectory()
os.system(File)
b = Tkinter.Button(top, text = 'DAQoutput', command= self.run)
b.pack()
top.mainloop()
I am interested to create a single tkinter GUI in which i can define a path to run a python script located in a particular folder. The code is shown below. It can read the required .py file from the set of files in that folder using the path i have given and open the dialogue box for plot graphs too but doesnt do anything. When i click the plot graphs button rather it gives an error "AttributeError: 'int' object has no attribute 'display_graph'". Can anyone check and edit my code to help.(I am using spyder so tk is tkr). I know about py2exe, So i would appreciate if someone can help with tkinter GUI code. Thanks
My python script is Empdata.py and i used def display_graph(data) in it:
Code
import glob
import tkinter as tkr
import os
path = r'C:\Users\C253271\Desktop\Empower data\\'
allpyfiles =glob.glob(os.path.join(path, "*.py"))
for file in allpyfiles:
file =('Empdata')
def graph():
global v
file.display_graph(v.get())
root = tkr.Tk()
v = tkr.StringVar()
tkr.Button(root, text='Close',command=root.destroy).grid(row=2, column=1)
tkr.Button(root, text='Plot Graphs', command = graph).grid(row=2, column=0)
root.mainloop()
In the code from the question, file is a string. It thus does not have any methods. What you really want to do is to import the python file, such that its content is available.
To do so, you may use importlib
f = importlib.import_module("Empdata") # if you have Empdata.py in your folder
f.some_method()
Your example should therefore look something like
import Tkinter as tkr
import importlib
fn = "Empdata"
f = importlib.import_module(fn)
def graph():
global v
f.display_graph(v.get())
root = tkr.Tk()
v = tkr.StringVar()
tkr.Button(root, text='Close',command=root.destroy).grid(row=2, column=1)
tkr.Button(root, text='Plot Graphs', command = graph).grid(row=2, column=0)
root.mainloop()
I'm using jupyter notebook on mac, recently I need to write interactive dialog box, so after google, I use Tkinter to make an interactive window.
But I was bothered by this problem couples day ,and still can't find a solution way.
Fisrt example:
from Tkinter import *
from tkFileDialog import askopenfilename
import sys
import os,time
def callback():
name= askopenfilename()
print name
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Second example:
from Tkinter import *
import sys,os
class YourApp(Tk):
def quit_and_close(self):
app.quit()
#os._exit(0)
#sys.exit(1)
#exit(0)
app = YourApp()
app.title('example')
app.geometry('400x300+200+200')
b = Button(app, text = "quit", command = app.quit_and_close)
b.pack()
app.mainloop()
And the third one:
import Tkinter as tk
import tkMessageBox
def ask_quit():
if tkMessageBox.askokcancel("Quit", "You want to quit now? *sniff*"):
root.destroy()
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", ask_quit)
root.mainloop()
After running those above code, always need have to force quit python launcher.
It is very weird, and annoying because after forcing quit, I will got the error:
Is it necessary to use python launcher as default window?
Is there possible to set another window to open ?
or is there proper way to close the launcher without causing programming crash?
p.s Even I try to use wxpython, it still open python launcher and got the same problem.
I've a GUI which will perform some functions when the buttons are pressed.
now i want to create a button in the GUI which will call and run a shell script in the background.
how can i achieve this ?
Not sure if your question is about how to call a shell script in Python, or how to make a button in your GUI. If the former, my comment above (recommending some research on subprocess.Popen) is the solution. Otherwise:
# assuming Python3
import tkinter as tk
import subprocess as sub
WINDOW_SIZE = "600x400"
root = tk.Tk()
root.geometry(WINDOW_SIZE)
tk.Button(root, text="Push me!", command=lambda: sub.call('path/to/script')).pack()
Python can run shell scripts using the supbprocess module. In order to run it in the background you can start it from a new thread.
To use the module
import subprocess
...
subprocess.call(['./yourScript.sh'])
For a good python threading resource you can try: How to use threading in Python?
Adding to what #lakesh said, below is the complete script :
import Tkinter
import subprocess
top = Tkinter.Tk()
def helloCallBack():
print "Below is the output from the shell script in terminal"
subprocess.call('./yourscript.sh', shell=True)
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
Please note that the shell script is in the same directory as that of the python script.
If needed, do chmod 777 yourscript.sh
subprocess.call('./yourscript.sh', shell=True)
and import Tkinter and not import tkinter solved the problems I was facing.
Use Tkinter to create a button. For more info, look at this video:http://www.youtube.com/watch?v=Qr60hWFyKHc
Example:
from Tkinter import *
root = Tk()
app = Frame(root)
app.grid()
button1 = Button(app,"Shell Script")
button1.grid()
root.mainloop()
To add the functionality:
change button1 line to:
button1 = Button(app,"Shell Script",command=runShellScript)
def runShellScript():
import subprocess
subprocess.call(['./yourScript.sh'])
I have a tkinter script. I was wondering is there anyway to have is so when you hit a button it takes you to a Web Site
from tkinter import *
app = Tk()
app.geometry("250x400")
app.title("Links")
def Link():
?
button1 = Button(app, text = "To a web site.", command = Link)
button1.pack()
app.mainloop()
There's a module for that.
import webbrowser
webbrowser.open("http://xkcd.com/353/")
Use webbrowser module to open the URL. The documentation: https://docs.python.org/3/library/webbrowser.html
# You can use open
from webbrowser import open
def link():
open('https://www.youtube.com/')
# You can use open_new_tab
from webbrowser import open_new_tab
def link():
open_new_tab('https://www.youtube.com/')