Python Ttkinter project not working when converted to .exe - python

i have created a small mining bot for minecraft and for user friendliness (for my friends) i used Tkinter for the app. When i run my app in python it works great, just as expected, but when i turn it into an .exe file (using PyInstaller) it suddenly doesn't work anymore. It just opens a random console and hides the console after a few seconds. To convert my file to .exe i used the following command in the command prompt: "python -m PyInstaller test.py" or "python -m PyInstaller test.py --onefile". Does anybody have any idea whats going on? For anyone interested, here is the code. Any help is appreciated!
import keyboard
import pyautogui
from time import sleep
import tkinter as tk
delay = 5
# program
def INIT():
window = tk.Tk()
window.title("Minecraft Mining Bot")
Stop_Key_Button = tk.StringVar()
Stop_Key_Button.set("i")
Greeting_Label = tk.Label(
text="Hello, user! To start using this program, please make sure to enter your stop key on your keyboard. Goodluck!",
foreground="white",
background="black"
)
Greeting_Label.pack()
Set_Key_Label = tk.Label(
text="Your current stop key is:",
foreground="white",
background="black"
)
Set_Key_Label.pack()
Display_Key = tk.Label(
textvariable=Stop_Key_Button,
foreground="white",
background="black"
)
Display_Key.pack()
Set_Key_Input = tk.Button(
text="Click on this to enter your new key",
foreground="white",
background="black",
command = lambda: SET_KEYBIND(Stop_Key_Button)
)
Set_Key_Input.pack()
Start_Button_Label = tk.Label(
text="To start the bot, press the button below. You then have 5 seconds to open minecraft and it will start! To stop the bot please press your button you put in.",
foreground="white",
background="black"
)
Start_Button_Label.pack()
Start_Button = tk.Button(
text="Click on this to start the bot with a 5 second delay!",
foreground="white",
background="black",
command = lambda: START_ROBOT(delay, Stop_Key_Button)
)
Start_Button.pack()
window.mainloop()
def SET_KEYBIND(Stop_Key_Button):
while (1):
key = keyboard.read_key()
if (key != None):
Stop_Key_Button.set(key)
print(Stop_Key_Button.get())
return
def START_ROBOT(delay, Stop_Key_Button):
sleep(delay)
keyboard.press("ctrl")
keyboard.press("w")
pyautogui.mouseDown()
while(1):
if(keyboard.is_pressed(Stop_Key_Button.get())):
keyboard.release("w")
keyboard.release("ctrl")
pyautogui.mouseUp()
break
sleep(0.1)
if __name__ == "__main__":
INIT()

use this command to convert it to exe with gui support and without console
pyinstaller.exe --onefile --windowed --icon=icon.ico app.py
if you want tkinter default icon, remove --icon=icon.ico

Aparently it was actually my fault, in short: i used the wrong python script (i was working with multiple but i only wanted to convert 1 file). I accidently kept converting a file with only 5 lines of code and not the file i actually wanted to convert. Thanks for the help because else i didint know all those arguments!
So in the end i only used python -m PyInstaller --onefile --windowed --icon=icon.ico main.py

Related

Exit button doesnt work after executeing ping command but does before doing so (tkinter)

So im very new to python and I'm basically trying to make a program were the user inputs a targets IP and then presses a button below to Execute the command (start the pinging process) and this I've done successfully but now I wanted to add an exit button below to stop the pinging process but I've got a problem. The button works fine before you press execute (works as intended it closes the application window) but when the script is running the button doesn't work at all and just kinda crashes the window but keeps the command running. How can I make the button work att all times (make it work when the script is running).
import tkinter as tk #import tkinter and tkinter library
from tkinter import ttk #package to style widget
import subprocess
def window(): #runs the window ??? i think
#address = input("Enter Ip Here:")
subprocess.call(f"ping {text.get()} -t -l 65500")
# root window
root = tk.Tk() # root?
root.geometry('200x200') #window size
root.resizable(False, False) # makes window non rezisable
root.title('Ping Of Death') #window title
var = tk.StringVar #variable tkinter = StringVar
text = tk.Entry(root,textvariable=var, width = 25)
text.pack()
# execute button
execute_button = ttk.Button( #defines the execute button
root,
text='Execute', #defines the text on the button
command=window
)
execute_button.pack( #package for button
ipadx=5, #x size
ipady=5, #y size
expand=True # ???
)
exit_button = ttk.Button(
root, text="Exit" ,
command=root.quit
)
exit_button.pack(pady=20)
root.mainloop() #to keep everything in a loop
I'm pretty sure that subprocess.call is blocking, so search on "subprocess.call non-blocking" and asyncio as an alternative.

My program is closes as soon as it opens in Python 3.8.8 (tkinter)

I have created a small GUI program using tkinter (Python 3.8.8) however when I create an .exe file using this command in the cmd : pyinstaller --onefile myprogram.py. It does create the executable file however when I click this .exe file, it close the program as soon as it start to executes. To resolve that issue I have tried the following:
I have put Input("Enter any key to end") in the end of the code.
I have run the command without using --onefile in CMD.
It does not show any error in the console. When I run my code in spyder IDE, It does not cause any issue.
Please guide me how do I configure that .exe file to not to close the program.
def click():
df = pd.read_csv("meta.csv")
State = df["State"]
# Ask for the directory where you want to save the file
paths = askdirectory(title='Select Folder')
print(paths)
dt = datetime.now()
# Mapping of TextBox
entered_text = txtSurName.get()
# Final file name format will be like: DateTime+Surname.csv
dt_res = dt.strftime("%d-%b-%Y%H%M%S%f")
dt_res = "/"+ dt_res + entered_text +".csv"
dic = {'state' : State}
df = pd.DataFrame(dic)
df.to_csv(paths+dt_res)
window = Tk()
window.configure(background="black")
# Labels and their value assigment
Label(window, text="Enter Surname ", bg="black",fg="white", font="none 12 bold").grid(row=1,column=0,sticky=W);
txtSurName = Entry(window, width=50, bg="white");
txtSurName.grid(row=2, column=0, sticky=W);
# Button
Button(window, text="Submit" , width = 6, command=click).grid(row=6,column=0,sticky=W);
#GUI LOGIC
window.mainloop()
input('Press ENTER to exit')

How run a python console script from a hiding console python script?

I'm not very experienced in python and I start building an app with Tkinter.
Like it's a window project I open it with pythonw.exe but it call a console script and I can't display the console of the second script if the first is hidden ...
There is the piece of code which call the second script :
from selenium_script import main
self.btn_downloadAnime = tk.Button(self.frm_addAnime, text='Lunch download script with voiranime.com links',
bg=self.colorBTN, font=22, activebackground=self.colorBG, height=2, width=50,
command=main)
Is this what you are looking for:
main.py:
import tkinter as tk
import subprocess
import sys
COMMAND = "start python selenium_script.py"
def start_new_proc():
proc = subprocess.Popen(COMMAND, close_fds=False, shell=True)
root = tk.Tk()
button = tk.Button(root, command=start_new_proc, text="Start new process")
button.pack()
root.mainloop()
selenium_script.py:
user_input = input(">>> ")
print("You typed this: " + str(user_input))
input("Press enter to exit.")
I start a new process using subprocess.Popen. The new process starts with its own shell (because of the "start" in the COMMAND variable)
Yes, I was missing the notion of process ...
The previous solution works and I found one too :
def open_selenium(self):
subprocess.Popen(args=['python', 'selenium2.py'], stdout=sys.stdout)

Python 3.6 tk ScrolledText on TopLevel won't insert

I am having issues with the code below when I use Pyinstaller to compile an executable.
I am attempting to open a second GUI window using TopLevel, adding a ScrolledText widget to it, then take the output of ipconfig /all and put it in the ScrolledText.
I stripped the code down to just the code relevant to this issue. If I run the python file directly, or compile with Pyinstaller without the --windowed command pyinstaller --onefile toolbox.py, then everything appears to work.
When I compile with --windowed pyinstaller --onefile --windowed toolbox.py, then the TopLevel window opens and I get the error message listed in the code and the ScrolledText widget is blank.
I have confirmed that using a normal string on the txt.insert command does work, so the issues appear to be with the os.popen command. I did attempt to use subprocess.check_output in place of os.popen but I get the same error message. Also, assigning the os.popen command to a variable then inserting the variable in txt.insert has the same result.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import scrolledtext
import os
import sys
def netIPInfo():
"""Open a second window, displays output of ipconfig /all."""
window2 = Toplevel()
window2.title("NIC IP Info")
window2.geometry("663x650")
txt = scrolledtext.ScrolledText(window2, width=80, height=40)
txt.pack(expand=1, fill="both")
try:
txt.insert(INSERT, os.popen("ipconfig /all").read()) # ISSUE!!
except:
e = sys.exc_info()
messagebox.showinfo("Error", e) # Error message below
# {<class 'OSError'}
# {[WinError 6] The handle is invalid}
# {<traceback object at 0x02EEB260>}
txt.configure(state="disabled")
window2.mainloop()
# Primary GUI Window
window = Tk()
window.title("ProTech QST")
tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control)
tab_control.add(tab1, text='Network')
lfr5 = ttk.LabelFrame(tab1, text="Information")
lfr5.pack(fill=X)
btn30 = Button(lfr5, text="NIC IP Info")
btn30.config(width=18, command=netIPInfo)
btn30.grid(column=0, row=1, sticky=W)
tab_control.pack(expand=1, fill="both")
if __name__ == "__main__":
window.mainloop()
EDIT
I was playing with the code some more and found that if I run pyinstaller with --windowed but without --onefile it works. Same for running pyinstaller with --onefile but without --windowed. So is this an issue not with the code, but with pyinstaller?

Python Tkinter checkbox value not changing

I'm sure I'm doing something ridiculous, but I can't seem to figure out what it is. I've never programmed in Python before.
Anyway, I have a variable for my checkbox value, but the value of it doesn't change when clicking on the checkb. It always prints out 0. Any help would be greatly appreciated.
Running on Ubuntu 13.10 Python 2.7
program.py
from Tkinter import *
class Program:
def __init__(self):
top = Tk()
self.chk1Checked = BooleanVar()
chk1 = Checkbutton(top, text = "Testing", variable = self.chk1Checked)
chk1.pack()
btn1 = Button(top, text = "Click Me", command = self.btn1CallBack)
btn1.pack()
top.mainloop()
def btn1CallBack(self):
print self.chk1Checked.get()
if __name__ == "__main__":
Program()
It is a problem with my editor(IEP). When running from the command line everything works fine.
I was able to get it to work in IEP after changing my startup script to the program.py file. instead of just running the file itself. Not sure why this fixes it.

Categories