Making a GUI File Downloader with Python 3 and Tkinter - python

(I am using python 3.6.6 if that matters to anyone)
I am making a GUI installer for a game that is currently in private alpha and is constantly updating.
I already made a console version:
from tqdm import tqdm
import requests, os, sys, zipfile, shutil, subprocess
chunk_size = 1024
url = "{LINK TO FILE YOU WANT TO DOWNLOAD}"
r = requests.get(url, stream = True)
total_size = int(r.headers['content-length'])
print("Are you sure you want to download the newest version of RFMP?")
print("y/n", end=': ')
answer = input()
while True:
if answer == 'y':
if os.path.exists("RFMB6_WINDOWS"):
print('')
print('')
print('Removing old RFMP files...')
subprocess.check_call(('attrib -R ' + 'RFMB6_WINDOWS' + '\\* /S').split())
shutil.rmtree('RFMB6_WINDOWS')
print('')
print('Removed old files.')
break
else:
break
elif answer == 'n':
sys.exit()
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
print('')
print('')
print('Downloading:')
with open('RFMB6_WINDOWS.zip', 'wb') as f:
for data in tqdm(iterable = r.iter_content(chunk_size = chunk_size), total = total_size/chunk_size, unit = 'KB'):
f.write(data)
print('')
print("Download Complete.")
print('')
print('')
print("Would you like to extract it?")
print("y/n", end=': ')
answer2 = input()
while True:
if answer2 == 'y':
print('')
print('')
print('Extracting...')
zip_ref = zipfile.ZipFile("RFMB6_WINDOWS.zip", 'r')
zip_ref.extractall("RFMB6_WINDOWS")
zip_ref.close()
print('')
print('Extraction Complete')
print('')
print('')
print('Cleaning up...')
os.remove("RFMB6_WINDOWS.zip")
print('')
print('Done! You have succesfully installed the newest version of the Ravenfield Multiplayer Private Alpha.')
break
elif answer2 == 'n':
print('')
print('Done! You have succesfully downloaded the newest Zip of the Ravenfield Multiplayer Private Alpha.')
break
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
os.system('pause')
I will only be using this to download 1 specific link so ignore the url variable.
I am trying to make a GUI that does the same thing when I click a button that says 'Download'. I want to make a progress bar, and a text box that tells you what is going on e.g. Downloading, extracting etc. I have no need for a directory option. I just need it to download where ever the file is located and delete the old file if it is still there.
So here is my question: How do I learn how to do this? I have looked at tkinter tutorials and other questions but I only find stuff for python 2 or stuff that is to developed to modify and call my own work. What I am looking for are links and/or examples that can tell me how I go about creating something like this. Thanks in advance to anyone who helps me out.
P.S. I am a noob when it comes to coding so whatever you explain please do it thoroughly.
P.S.S. In order to run the console application you need to run it through terminal and add your own link in the 'url' variable.

Take a look at PySimpleGUI. You can build a layout with a download button, an output window and a progress bar easily. Stop by the GitHub and post an issue if you run into trouble.

The documentation for Tkinter with Python3:
https://docs.python.org/3/library/tk.html
This answer might help you out:
How to create downloading progress bar in ttk?
documentation: https://tkdocs.com/tutorial/morewidgets.html#progressbar

Related

Why am I getting an "No maching processes were found" error upon executing this python file?

I am working on a project in Python. Currently, only Option 1 works. (i just started this project) It goes through two levels of input and then runs a shell command that makes MacOS show a hidden file. But I am getting an error in the Macos Terminal upon running it: "No matching processes were found." Do you have any idea on why it could be doing this?
My code is too large to fit here, so here is a pastebin link: https://pastebin.com/EuBJjge6
#!/usr/bin/env python
import os
#function by popcnt on stackoverflow
def clear():
os.system('cls' if os.name =='nt' else 'clear')
# thanks to No Spoko on StackOverflow for the original idea, what you see here is modified
def printLogo():
f = open('logo.txt', 'r')
logo = f.read()
print(logo)
f.close()
clear()
printLogo()
print('Welcome to Belowdeck! \n')
#some code ideas from stackoverflow, don't remember the user
menuItem = {}
menuItem['1']="Show hidden files and folders"
menuItem['2']="Hide a file or folder from view"
menuItem['3']="Download files without a web browser"
menuItem['4']="List contents of a folder"
menuItem['5']="View any file's contents"
menuItem['6']="Change permissions of a file"
menuItem['7']="Restore a disk image to a device connected to your Mac"
menuItem['8']="Change the default screenshot location"
menuItem['9']="Change the default screenshot format"
menuItem['10']="Stop apps from syncing to iCloud by default"
menuItem['11']="Check for macOS updates every day instead of every month"
menuItem['12']="Enable a sound when your Mac connects to a power source"
menuItem['13']="Make holding down a key repeat characters"
menuItem['14']="Dull hidden apps in your Dock"
menuItem['15']="Hide non-active apps in your Dock"
menuItem['16']="Add a spacer to your Dock"
menuItem['17']="Change the delay before your Dock slides out"
menuItem['18']="Change the speed at which your Dock slides out"
menuItem['19']="Disable auto-restore in the Preview app"
menuItem['20']="Add a message to the login window"
menuItem['21']="Get rid of Dashboard"
menuItem['22']="Rebuild Spotlight"
menuItem['23']="Destroy your Mac \n"
options=menuItem.keys()
sorted(options)
for entry in options:
print (entry, menuItem[entry])
def option1():
clear()
print("Show hidden files and folders \n")
selection1=input("Would you like to proceed with the operation? (y/n): ")
if selection1 == "y" or selection1 == "Y":
os.system("defaults write com.apple.finder AppleShowAllFiles -bool TRUE && killall finder")
else:
input('Invalid selection! ')
while True:
menuSelection=input("Please select your desired action:")
if menuSelection =='1':
option1()
elif menuSelection == '2':
print ("delete")
elif menuSelection == '3':
print ("find")
elif menuSelection == '4':
print ('4')
else:
print ("Invalid action!")
I don't have access to a Mac, but Googling that error message throws up a lot of hits where people have had issues trying to kill processes. It's very likely that the issue is in line 59. Make sure the commands are correct. Also, avoid using os.system() call to execute shell commands -- it is not recommended. Use the subprocess module instead.
https://docs.python.org/3/library/subprocess.html#subprocess-replacements
https://www.youtube.com/watch?v=oQxTSDh-ECk

How do I detect if a user is using my file for the first time?

I'm making a Python file, and I want a different screen to show up for someone who is opening the file for the very first time, other than a recurring visitor. Like so:
if USER_NEW:
print('New user screen')
else:
print('other screen')
Exactly how would I go about this?
You would need to store the information in another file to read later, when your script is run again. When you run your script you need to read this file and see if contains a value to say the visitor has already looked at the file or write in it to tell the program when they have during the next visit.
For example:
with open('user.txt', 'r+') as file:
if file.read() == '':
print('New user screen')
else:
print('other screen')
file.write('visited')
You can save program information in a state file. Where to do that depends on the operating system and even then you'll find disagreement. On windows you can use the environment variable %LOCALAPPDATA%. On most unixy systems you can use ~/.myapp or perhaps ~/.config/myapp (I like the second much better). I don't know the conventions on other machines.
You also need to establish a convention for the format of the file. I'm just going to look for a file name.
import platform
import os
import time
if platform.system() == "Windows":
my_app_path = os.path.expandvars("%LOCALAPPDATA%/myapp")
elif platform.system() == "Linux":
my_app_path = os.path.expanduser("~/.config/myapp")
else:
exit(2)
first_run_file = os.path.join(my_app_path, "first_run.txt")
if not os.path.exists(first_run_file):
first_run = True
os.makedirs(my_app_path)
open(first_run_file, "w")
else:
first_run = False

Python file-reader will not run in IDLE but works fine in terminal?

So I created this lab assignment for class. It seemed fine, except for it doesn't run at all in idle. Idle opens, and then immediately closes. It ran fine in powershell, and the IDE i was using, but would not run at all for my professor.
The program just opens randomNumbers.txt and then lists the values inside. I have had no problems with any of my programs before this one, and this one seems to be the simplest. Is there a simple mistake I'm overlooking? As well as that, if you have any suggestions as to methods i can use to optimize this code id love the suggestions, I've been using python for 2 months now.
Sorry if this post was a bit long, just really confused.
import time, sys
def main():
global file
file = open("randomNumber.txt","r")
prepArray()
print("\n-----------\n# | Value\n-----------")
printArray()
file.close()
closeInput = input("\nPress ENTER to exit")
print("Closing...")
def prepArray():
global numberSplit
global file
openFile = input("Open randomNumber.txt (Y/N): ")
print("\n")
if openFile.lower() == "y":
try:
f = open("randomNumber.txt","r")
except IOError:
print("Error opening file: Did you run the generator first?")
main()
elif openFile.lower() == "n":
sys.exit()
else:
print("\nInvalid input, enter either (Y for yes, N for no)\n")
main()
numberSplit = file.readline()
numberSplit = numberSplit.split(",")
numberSplit = numberSplit[:-1]
def printArray():
global numberSplit
lineCount = 1
totalCount = 0
for item in numberSplit:
print(lineCount,"-",item)
lineCount += 1
totalCount += float(item)
print("\nTotal:",round((totalCount),2))
main()
randomNumbers.txt just contains
119.18,470.54,159.89,360.56,47.15,489.77,242.54,
I was testing your code and its work fine! I'm sure your problem is you haven't randomNumbers.txt in the same folder, please try to put your txt file in the same folder where is your script and it'll work! ;-)

open games on ubuntu from python script

i am building a python script that can do certain tasks. I am now focusing on opening and application from the script i used subprocess.call and os.startfile but nothing helped and returned error the code is-
import os
while True:
message=raw_input("Enter your message >> ")
if message=="quit":
exit()
elif message=="bye":
exit()
elif message=="bye bye":
exit()
elif message=="good bye":
exit()
elif message=="see u":
print "Okay then :)"
exit()
elif message=="open games":
print "on to that"
os.start(gnome-mines)
Any help is appreciated
os.startfile is only available with Windows.
Please check here !!!
Instead of os.startfile, use os.system.
Make sure file and user has execution permissions.
you have to enter the complete path of the file to be opened
elif message=="open games":
print "on to that"
os.system("/usr/games/gnome-mines")

Script writes in reverse

Sorry if I asked this wrong or formatted it wrong, this is my first time here.
Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:
Hi, my name
is bob.
But, it writes:
is bob.
Hi, my name
How can I fix this?
The code is here:
import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
editor()
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
lowlevelinput()
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")
lowlevelinput()
Nice puzzle. Why are the lines coming out in reverse? Because of output buffering:
When you write to a file, the system doesn't immediately commit your data to disk. This happens periodically (when the buffer is full), or when the file is closed. You never close f, so it is closed for you when f goes out of scope... which happens when the function editor() returns. But editor() calls itself recursively! So the first call to editor() is the last one to exit, and its output is the last to be committed to disk. Neat, eh?
To fix the problem, it is enough to close f as soon as you are done writing:
f = open(usrtxtdir,"a")
f.write(words + '\n')
f.close() # don't forget the parentheses
Or the equivalent:
with open(usrtxtdir, "a") as f:
f.write(words + '\n')
But it's better to fix the organization of your program:
Use a loop to run editor(), not recursive calls.
An editor should be writing out the file at the end of the session, not with every line input. Consider collecting the user input in a list of lines, and writing everything out in one go at the end.
If you do want to write as you go, you should open the file only once, write repeatedly, then close it when done.
You need to close your file after writing, before you try to open it again. Otherwise your writes will not be finalized until the program is closed.
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
f.close() # your missing line!
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
If you replace:
f = open(usrtxtdir,"a")
f.write(words + '\n')
with:
with open(usrtxtdir,"a") as f:
f.write(words + '\n')
It comes out in order. Pretty much always use with open() for file access. It handles the closing of the files for you automatically, even in the event of a crash. Although you might consider taking text in memory and writing it only upon quit. But that's not really part of the problem at hand.
Python's file.write() documentation states: "Due to buffering, the string may not actually show up in the file until the flush() or close() method is called"
Since you're recursively reopening the file and writing to it before closing it (or flushing the buffer), the outer value ('Hi, my name') isn't yet written when the inner frame (where you write 'is bob.') completes, which appears to automatically flush the write buffer.
You should be able to add file.flush() to correct it like this:
import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
f.flush() # <----- ADD THIS LINE HERE -----< #
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
editor()
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
lowlevelinput()
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")
lowlevelinput()
Also, don't forget to close your file after you're done with it!

Categories

Resources