Menu interferring with save prompt - python

I am experiencing an issue where if I introduce a user choice menu into my code, a function that produces a save dialog will not appear. If I comment out the menu function then everything works.
A sample of my code is below. I have ripped out a lot of other functions so only the minimum is presented below and will not make any sense but the code does work when commenting out the save_forms def.
I've only been at this for a few weeks so any constructive criticism would be appreciated.
import time
import sys
from tkinter import *
from tkinter import filedialog as fd
global OU
global tempdir
global fs
def menu():
print("[1] Number 1")
print("[2] Number 2")
print("[0] Exit")
ou_option = int(input("Enter a number: "))
if ou_option == 1:
print("Number 1 selected")
OU = str("Number1")
elif ou_option == 2:
print("Number 2 selected")
OU = str("Number2")
elif ou_option == 0:
print("Exiting")
time.sleep(1)
sys.exit()
else:
print("Invalid number. Try again...")
menu()
def save_forms():
tk2 = Tk()
tk2.withdraw()
fs = fd.askdirectory(title='Select output folder')
if not fs:
print('User Cancelled')
time.sleep(1)
sys.exit()
else:
print('Saving...')
menu()
print("Saving Form")
save_forms()

Using tk1.attributes("-topmost", True) brings the dialog to the front.
Thanks Bill for the point in the right direction.

Related

Using tkinter's folder choosing dialog box twice

At the start of my code, I let the user choose a file and store its path in a text file. Here is the function for that:
def choose_folder():
root = tk.Tk()
root.withdraw()
global DIR
DIR = filedialog.askdirectory()
global settings_file # Somehow works without this line despite being declared in main
with open(settings_file, "w") as sf:
sf.write(DIR)
Now, I want to let the user change the folder. In the main loop, the user chooses an option each time. Option 4 is to change the directory. Here is my code to change it:
elif user_input == 4:
open(settings_file, "w").close() # Clear the settings file
choose_folder()
The problem is, that for some reason the folder choosing dialog box will not open the second time. I've already checked and the code reaches the choose_folder() function but stops running on filedialog.askdirectory() (the screen flickers for a second which means that something happens but doesn't open the dialog box). What causes this to happen and how can I fix it?
EDIT: Here's the code snippet (I have also slightly changed choose_folder()):
import tkinter as tk
from tkinter import filedialog
import os
#other imports
def prompt_continue() -> bool:
choice = input("Do you want to continue (y/n)? ")[0].lower()
while choice != 'y' and choice != 'n':
choice = input("Invalid Input. ")[0].lower()
return choice == 'y'
def choose_folder():
root = tk.Tk()
root.withdraw()
global DIR
DIR = filedialog.askdirectory()
while not os.path.isdir(DIR):
print("Please choose a folder.")
DIR = filedialog.askdirectory()
while os.listdir(DIR):
print("Please choose an empty folder.")
DIR = filedialog.askdirectory()
with open(settings_file, "w") as sf:
sf.write(DIR)
if __name__ == "__main__":
DIR = ""
settings_file = os.path.expanduser('~/Documents/flagdir.txt')
if os.path.isfile(settings_file): # if settings file exists
if os.stat(settings_file).st_size == 0: # if settings file is empty
choose_folder()
else:
choose_folder()
with open(settings_file, 'r') as file:
DIR = file.read()
user_continue = True
total = 0
while user_continue:
print("Choose option:")
print("[1] Download n random flags")
print("[2] Enter 2 countries and download their mashup")
print("[3] Clear the flags folder")
print("[4] Change the flags folder path")
print("[5] Print the flags folder path")
print("[6] Exit")
user_input = int(input())
while user_input < 1 or user_input > 6:
user_input = int(input("Invalid Input."))
if user_input == 1:
# working code
elif user_input == 2:
# working code
elif user_input == 3:
# working code
elif user_input == 4:
open(settings_file, "w").close()
choose_folder()
elif user_input == 5:
# working code
else:
break
user_continue = prompt_continue()
print("Bye!")

How do I break this infinite loop

Im trying to create a menu. The idea is to make the script loop back to the main menu when the number two is selected. It loops back but when i select number 1 it just keeps looping. How do i fix this.
import os
import sys
def mainmenu():
print """
this is a test menu
"""
mainmenu()
choice = raw_input("DMF>>")
if choice == '1':
def men1():
print """
this is the second menu
"""
men1()
def back():
men1_actions['mainmenu']()
men1_actions = {
'mainmenu': mainmenu,
'2': back,
}
while True:
choice2 = raw_input("DMF>>")
if choice2 == '2':
back()
I'm not sure with what you are pertaining to exactly but you can first define the functions and then just call on one raw_input to indicate whether the input is 1 or 2.
def mainmenu():
print """this is a test menu"""
def men1():
print """this is the second menu"""
while True:
choice = raw_input("DMF>>")
if choice == '1':
mainmenu()
elif choice == '2':
men1()
else:
print """Please choose between 1 or 2"""

Python: Functions is not running when called from a menu

I'm currently working on an small banking application in python. I created functions that opens a txt file. I tested the function on its own so I know it works, however when implemented alongside the menu it seems not to work.
def parse_in():
with open('bank.txt', 'r') as details:
lines = details.read().splitlines()
return lines
Later on I have a simple menu with few options but here I will only show the one I'm having issues with.
def menu():
print("Please selected one of the options" + "\n\t1: Open account"
while True:
try:
selection = int(input("Please enter your choice: "))
if selection == 1:
open_account(details)
else:
break
except:
print("Please enter number 1-6")
if 1 is selected an open account should be ran
def open_account(details):
print("Welcome to your new account")
new_account_number = randint(000000, 999999)
while True:
try:
new_account_balance = float(input("Enter your sum of money: "))
if new_account_balance < 0:
print("please enter positive value")
else:
break
except:
print("Please Enter Number Only")
while True:
new_account_name = input("Enter your name: ")
if " " in new_account_name:
print("Please enter your full name")
else:
break
details.append(new_account_number)
details.append(new_account_balance)
details.append(new_account_name)
After the information was imputed the idea is that they're suppose to save to the same file using a function.
def parse_out(details):
with open('bank.txt', 'w') as file:
for i in details:
file.write(str(i) + '\n')
and everything is ran in main function
def main():
details = parse_in()
welcome()
menu()
parse_out(details)
When I press 1 the open account function seems not be running instead, the menu loops back to choosing one of the options. I'n not really sure why it does that as it seems it should run and take information from user fallowed by saving the info to file.

Python program won't execute

I'm in the middle of making a small game involving hacking into people's computers, and stealing files and money in order to complete missions. Here is the code as of now:
#SICCr4k2: Broke
#
#
#
#Remember whenever you are printing a random ip address to add the "." in between each part of the ip (each random number)
## LAST LEFT ON HERE: MAKE BUTTONS FOR NODES
## MAKE FILES FOR NULL'S NODE
## SET THE CORRECT PLACEMENTS FOR ALL THE BUTTONS
## nullMain referenced before assignment
## make it so that you send a message through the prompt to get their ip, then it automatically puts the ip in the nodes
## window. Like you send the person a message, and then it gets the ip and puts it in the nodes window
## take away the buttons in the nodes window, just at labels where it points to the host's ip address.
import random
import time
import sys
import os
import tkinter as tk
from tkinter import *
#def nodes():
# nodeWindow = tk.Tk()
# frame = tk.Frame(nodeWindow, width=700, height=400)
# frame.grid_propagate(0)
# frame.grid()
# nodeWindow.title("||| Nodes |||")
# nullIp = tk.Label(nodeWindow, text="Ip: 221.153.52.216")
# nullIp.grid(row=0, column=0)
# nullMain = tk.Button(nodeWindow, text="Null", function=nullMainCallback())
# nullMain.config(height=1, width=100)
# nullMain.grid(row=0, column=0)
# def nullMainCallback():
# nullMain.destroy()
# nullIp = tk.Label(nodeWindow, text="Ip: 221.153.52.216")
# nullIp.grid(row=0, column=0)
#def commands():
def numbers():
number1 = random.randint(1, 99)
number2 = random.randint(1, 99)
print(number1)
if number1 != number2:
numbers()
if number1 == number2:
os.system('cls')
def ips():
nullIp = ('18.279.332')
def getIp():
x = random.randint(1, 222)
if x == 127:
x += 1
return '{}.{}.{}.{}'.format(
x,
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
def commandInput():
CommandInput = input(">>> ")
if CommandInput == ("myNodes()"):
nodes()
else:
commandInput()
commandInput()
def usernameCreation():
username = input(">>> ")
print("'" + username + "' is that correct?")
usernameInput = input(">>> ")
if usernameInput == ("yes"):
print("Okay...")
if usernameInput ==("no"):
usernameCreation()
def game():
def tutorial():
print('Hello.')
time.sleep(3)
print('Welcome back.')
time.sleep(3)
print('How was it?')
time.sleep(3)
print('Being hacked for the first time?')
time.sleep(3)
print("You're probably wondering who I am.")
time.sleep(5)
print("Well, my name is Null.")
time.sleep(3)
print("Only because I am well known for nothing.")
time.sleep(3)
print("Other than not being alive.")
time.sleep(3)
os.system('cls')
print("First thing's first, what shall I call you?")
usernameCreation()
print("Let's give you a bit of movement.")
time.sleep(3)
print("""The first thing you will want to do would be to connect to my computer, but
to do that, you have to find my ip address. Here. I just uploaded new software to your computer.""")
time.sleep(3)
print("""You will now be able to access my ip, nad many other's with a simple command. The command is
getIp(). Input that command below, but inside the parenthesis, you type in the screen name. For instance: getIp(Null).
type that command in to get my ip.""")
input(">>> ")
if ("getIp(Null)"):
numbers()
print("""My ip was just added to your nodes, which you can access by typing myNodes().""")
game()
I just want to note that when I run the program, it doesn't list any errors or anything, it just doesn't execute at all... Any ideas????
You define the function tutorial inside game (which you shouldn't really do – there's no point in defining it that way) but never call tutorial.
Inside of game you want to call tutorial:
def game():
def tutorial():
# code for tutorial
tutorial()
A better way to structure your code, however, is to use a main method (which is the standard way to start the execution of a program` and keep every other function separate. There's no need to nest functions as you've done.
So, for example:
def main():
tutorial()
# all other function definitions
def tutorial():
# code for tutorial
if __name__ == "__main__":
main()
You never call tutorial() although you shouldn't nest functions like this.

I have an error in python with tkinter and need help(school project)

I have to create a little text adventure for school in python.
To detect keyboard inputs I decided to use tkinter and disable the window.
All is working fine but if I try to calculate with a variable after a key was pressed, I get the following error...This is the error message
This is the script I am using(I don't have much experience with python...)
import os
import sys
import tkinter
menueeintraege = ["Start", "Steuerung", "Credits", "Beenden"]
index = 0
def menueaufbauen():
os.system("cls")
print("Menue")
print("")
print("")
for i in range(4):
if i == index:
print(menueeintraege[i] + "<")
else:
print(menueeintraege[i])
menueaufbauen()
def startgame():
os.system("game.py");
def steuerung():
os.system("cls")
print("Steuerung")
print("")
print("Norden = Pfeiltaste Hoch")
print("Sueden = Pfeiltaste Runter")
print("Osten = Pfeiltaste Rechts")
print("Westen = Pfeiltaste Links")
print("Bestaetigen = Enter")
def credits():
os.system("cls")
print("Credits")
print("")
print("Jannik Nickel")
print("Thomas Kraus")
print("")
def exitgame():
sys.exit()
def menueauswahl(taste):
print(taste)
if taste == "Up":
if index > 0:
index -= 1
print(index)
elif taste == "Down":
if index < 3:
index += 1
menueaufbau()
def tasteneingabe(event):
tastenname = event.keysym
menueauswahl(tastenname)
fenster = tkinter.Tk()
fenster.bind_all('<Key>', tasteneingabe)
fenster.withdraw()
fenster.mainloop()
I think the mistake have to be in the last part of the script, I hope someone here knows a solution because it's really important for school.
Thanks for any help
(I'm using Visual Studio 2015)
Okay so I caught a couple of errors. The first is that you are referencing a global variable (index) inside of a function. To do that, you need to tell python that you are using a global variable.
def menueauswahl(taste):
global index
print(taste)
And also you need to change the function name in line 61 to menuaufbauen().

Categories

Resources