MessageBox in DearPyGui - python

I am using the DearPyGui library for creating a user interface in python.
In a function that runs my algorithm, the algorithm needs some input from the user (yes/no question). Is it possible to easily implement such a messagebox in DearPyGui without braking the flow of the function?
Something like this:
def runAlgorithm():
a = 2 + 2
user_choice = dpg.messageBox("Do you want to add or subtract the values", ["add", "subtract"]
if user_choice == "add":
a = a + a
else:
a = a - a
print("The user has selected %s and the result is %d"%(user_choice, a)
As I understand DearPyGui until now, this is not possible and I have to write something like this, which is quite bulky and unreadable and especially in algorithms that might need some user input greatly disrupts their readability.
def choiceAdd(sender, app_data, user_data):
a = user_data[0]
print("The user has selected %s and the result is %d"%("add", a + a)
def choiceSub(sender, app_data, user_data):
a = user_data[0]
print("The user has selected %s and the result is %d"%("subtract", a - a)
def runAlgorithm():
a = 2 + 2
with dpg.window():
dpg.add_button("add", callback = choiceAdd, user_data = [a])
dpg.add_button("subtract", callback = choiceSub, user_data = [a]
user_choice = dpg.messageBox("Do you want to add or subtract the values", ["add", "subtract"]
if user_choice == "add":
a = a + a
else:
a = a - a
print("The user has selected %s and the result is %d"%(user_choice, a)
Any help is recommended.
Thank you in advance

Related

I want to add tkinter to this code and will do that but i don't know where to place the tkinter variables?, they will eventually be in the while true

my code should be looking for search options and appending to a list that compares to the search, all im trying to figure out is how to get tkinter in the loop, because i dont know where to put things such as the if name == "main":
stuff
from tkinter import *
ideas = ["pooop", "pooop", "yaaah"]
describe = ["A software that provides poop images", "Fart noises", "kid on crack"]
window = Tk()
window.title("Exists?")
while True:
function = input("Append or Search: ").lower().strip()
if function == "append":
appending = input("What would you like to append enter keywords/possible names..... ")
ideas.append(appending)
appending2 = input("Describe what you would like to append, please do not enter blank values as that will make "
"your software harder to find ")
describe.append(appending2)
print(ideas.index(str(appending)))
print(describe.index(str(appending2)))
searcher = input("What would you like to search for, enter keywords/possible names")
if searcher in ideas:
print(ideas)
print("description: " + describe[ideas.index(searcher)])
print(searcher in ideas)
numberOfResults = str(ideas.count(searcher))
print("0 results found")
if searcher not in ideas:
print(ideas)
print(searcher in ideas)
of = str(len(ideas))
print("0 results found of " + of)
if function == "search":
searcher = input("What would you like to search for, enter keywords/possible names")
if searcher in ideas:
print(ideas)
print("description: " + describe[ideas.index(searcher)])
print(searcher in ideas)
numberOfResults = str(ideas.count(searcher))
print(numberOfResults + " results found")
if searcher not in ideas:
print(ideas)
print(searcher in ideas)
of = str(len(ideas))
print("0 results found of " + of)
if __name__ == "__main__":
window.mainloop()
Put the code in an infinite loop and exit when a word other than append or search is entered
ideas = ["pooop", "pooop", "yaaah"]
describe = ["A software that provides poop images", "Fart noises", "kid on crack"]
while True: # infinity loop
function = input("Append or Search: ").lower().strip()
if function == "append":
pass # ... you code instead
elif function == "search":
pass # ... you code instead
else: # other input
print("That's all!")
break # exit loop

looping through task numbers

Could someone help with my current code. I would like to add task numbers to my tasks that get saved in my output text document. I would need to loop it so each task will be assigned the next task number. If possible I would like to be able to call on these task numbers later.
My code so far is:
def add_task():
if menu == "a" or menu == "A":
with open( 'user.txt' ) as fin :
usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
task = input ("Please enter the username of the person the task is assigned to.\n")
while task not in usernames :
task = input("Username not registered. Please enter a valid username.\n")
else:
task_title = input("Please enter the title of the task.\n")
task_description = input("Please enter the task description.\n")
task_due = input("Please input the due date of the task. (yyyy-mm-dd)\n")
date = datetime.date.today()
task_completed = False
if task_completed == False:
task_completed = "No"
else:
task_completed = ("Yes")
with open('tasks.txt', 'a') as task1:
task1.write("\nUser assigned to task:\n" + task + "\nTask Title :" + "\n" + task_title + "\n" + "Task Description:\n" + task_description + "\n" + "Task Due Date:\n" + task_due + "\n" + "Date Assigned:\n" + str(date) + "\n" + "Task Completed:\n" + task_completed + "\n")
print("The new assigned task has been saved")
add_task()
Firstly, I don't really want to go into detail but the way you are storing your output is highly inefficient and difficult to access the larger your text file gets. Why not use some free DB system to store your data.
Secondly. Assuming that you want to write many tasks at a time but only "save" once so to speak, consider using a dict of dicts.
def write_task_to_txt(task):
### break down the dict to from your lines to write to your text
def add_task(task_list,task_id):
new_tasks[task_id] = {}
new_tasks[task_id]["username"] = "username"
new_tasks[task_id]["title"] = "Task 1"
### How you fill up a task
return task_list
new_tasks = {}
for i in range(10):
new_tasks = add_task(new_tasks,i+1)
write_task_to_txt(new_tasks)
With this you can always access the task using new_tasks[task_id] to pull all the data of that task. Note the for loop is using an iterator. If you want to avoid this you could use a global and a while loop instead. BUT if you want to do that, i recommend converting your application into a class and use class variables instead.
Here is a skeleton of how I would try that:
class yourclass():
def __init__(self):
self.task_num = 1 #use 1 if no values
self.tasks_towrite = {}
self.mode_select()
def mode_select(self):
self.menu = input("choose mode")
while(1):
if self.menu == "a" or self.menu == "A":
self.add_task()
if self.menu == "s".casefold() #Cool function that does the same as your menu thingy
self.write_to_text()
else:
print("exit")
self.close_program()
def close_program(self): # Exit function
print("exiting")
sys.exit(1)
def add_task(self): #Add task
with open( 'user.txt' ) as fin :
self.usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
task = input ("Please enter the username of the person the task is assigned to.\n")
while task not in self.usernames :
task = input("Username not registered. Please enter a valid username.\n")
else:
new_task = {}
new_task["username"] = task
new_task["title"] = input("Please enter the title of the task.\n")
new_task["description"] = input("Please enter the task description.\n")
new_task["due"] = input("Please input the due date of the task. (yyyy-mm-dd)\n")
date = datetime.date.today()
task_completed = False
if task_completed == False:
new_task["completed"] = "No"
else:
new_task["completed"] = "Yes"
new_task["assigned"] = date
self.tasks_towrite[self.task_num] = new_task
sefl.task_num +=1 #New test number
return None #returns to mode_select
def write_to_text(self):
with open('tasks.txt', 'a') as task1:
for i in self.tasks_towrite:
task1.write(str(i) + "\n") #Writes it all at once You can reformat however you want
self.tasks_towrite = {}
print("The new assigned tasks has been saved")
return None #returns to menu or you could go to self.close_program to exit
if __name__== '__main__':
x = yourclass()

Start() is not defined

Hey I am trying to create a simple text based slot machine with the view to convert it into a graphical one latter.
I have started by it prompting a menu which works fine. However when the user enters the required 'p' to continue it won't call the next function because I haven't defined it yet.... I have?
from time import sleep
from random import shuffle
#Creates the class
class Machine():
#This is the constructor full of attributes
def __init__(self):
self.reel1 = ["Lemon", "Bell", "Cherry"]
self.reel2 = ["Lemon", "Bell", "Cherry"]
self.reel3 = ["Lemon", "Bell", "Cherry"]
firstSlide = self.reel1
secondSlide = self.reel2
thirdSlide = self.reel3
self.currentFunds = "10"
funds = self.currentFunds
f = open('score.txt', 'w')
f.write(funds)
#Dictates all the funds and checks if the user has enough money or needs to add money
def Funds(self):
if self.currentFunds == "0":
print("You are out of credits! :( \n")
Menu()
#Starts the spinning and randomizes the lists
def Start(self, firstSlide, secondSlide, thirdSlide):
shuffle(firstSlide, secondSlide, thirdSlide)
print(firstSlide[0], secondSlide[1], thirdSlide[3])
#Intro Menu to give player stats and options
def Menu(self):
play = ""
m = Machine()
print('*****************\n')
print(' WELCOME! \n')
print('*****************\n')
print('Current Credits: ', m.currentFunds)
if input("Press P to play \n") == "P" or "p":
machine = Start()
machine.Start()
machine = Machine()
while True:
machine.Menu()
Any ideas?
You have Start as a member function of the Machine class. You need to replace machine = Start() with self.Start().
It actually looks like this is the case with a number of the variables you seem to be trying to use. For example, I would expect that Start would rely on self.start, but it is relying on parameters (which you are not passing in).
As a general comment on this code, I'm wondering if you really need/want to have this be structured this way. You seem to be creating the object recursively and I think you might be better off restructuring a bit.

Problems transferring information from one part of a function to another

While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:

Beginner-level virtual library program troubles, how do I let the user create an array or 'def'? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Alright, so I'm bad with words so I painted you all a beautiful picture hoping that whole picture is worth a thousand words thing is true:
However, if the picture didn't do the job I'll try to describe my issue. I'm trying to make a sort of beginner level virtual library in Python. However, first here is my code thus-far:
book_title = []
book_page_count = []
book_publish_date = []
book_author = []
def elsePhrase():
print("Wrong input, I'll just send you back to the menu.\n")
menu()
def menu():
print("- - - - - - - -- PROGRAM MENU -- - - - - - - -")
print("Welcome Book Sorter, what would you like to do? \n")
print("1 ) Add a book")
print("2 ) List a specific book's details")
print("3 ) List all recorded complete book details")
menu_Choice = input("4 ) Exit.\n\n")
if menu_Choice == 1:
add_book()
elif menu_Choice == 2:
list_book()
elif menu_Choice == 3:
list_all()
elif menu_Choice == 4:
exit()
else:
print("Error: Please enter a number as shown and try again.")
print("-----------------------------------------------------------\n\n")
menu()
def add_book():
print("\nYou selected: Add book. Please fill out the following information: \n")
title = raw_input("Book title: ")
book_title.append(str(title))
page_count = raw_input("Book page count: ")
book_page_count.append(page_count)
publish_date = raw_input("Book publish date: ")
book_publish_date.append(publish_date)
author = raw_input("Book author: ")
book_author.append(author)
print("\nProcess complete.")
Restart()
def list_book():
# Find out how to fix this
print("You selected: list book. Please select a book from below: ")
print(book_title)
choice = raw_input("\n")
def list_all():
#Find out how to make this actually look not-shitty and make sense.
print(book_title)
print(book_page_count)
print(book_publish_date)
print(book_author)
def Restart():
toMenu = raw_input("\n\tWould you like to go back to the main menu? Y / N\t\n\n")
if toMenu == "Y":
menu()
elif toMenu == "N":
toExit = raw_input("Oh.. Okay then want me to just exit the program? Y /N\n\n")
if toExit == "Y":
exit()
elif toExit == "N":
print("Alright, I guess I'll just leave you be, you know where the big red X button is I guess. Take your time.")
else:
elsePhrase()
else:
elsePhrase()
def main():
menu()
main()
Yeah, it's bad I know, I'm sorry; I am still trying to learn.
Anyway, where I am having trouble is I want to basically create a unique array or 'def' that has all this information in it.. So say for example I want to add a book into this library it will make a block of information that holds the title, author, page count, publish date, etc.. All together in a comfortable little box of information I can call later. The issue is I have no idea how to actually do this with an undetermined amount of information defined by the user.
So.. That about sums it up I guess, thanks very much in advance for any help!
TL;DR: I don't understand how to let the user enter a block of seperate information (Title, author, page count, etc..), bind it all together, and then print it out again on demand easily(Saying "Find details on X and Y" where X is book 1 / all the information entered in step 1 and Y is all the information on book 2 in a different step 1. All done multiple-infinite times.
I hope this made sense, please free to ask me anything, I just would really like to be able to do this, thanks!
Here is some code that should get you well on your way:
import sys
# Python 2/3 compatibility shim
if sys.hexversion >= 0x3000000:
inp = input
rng = range
else:
inp = raw_input
rng = xrange
def get_int(prompt):
while True:
try:
return int(inp(prompt))
except ValueError:
pass
class Book:
#classmethod
def from_prompt(cls):
title = inp('Enter title: ').strip()
author = inp('Enter author: ').strip()
pages = get_int('Page count: ')
date = inp('Publication date: ').strip()
return cls(title, author, pages, date)
def __init__(self, title, author, pages, date):
self.title = title
self.author = author
self.pages = pages
self.date = date
def __str__(self):
return "Book: {title}\nAuthor: {author}\nPage count: {pages}\nPublish Date: {date}".format(
title=self.title, author=self.author, pages=self.pages, date=self.date
)
class Library:
def __init__(self, books=None):
self.books = []
self.title_index = {}
if books:
for book in books:
self.add(book)
def add(self, book):
self.books.append(book)
self.title_index[book.title] = book
def find_title(self, title):
return self.title_index.get(title, None)
def __str__(self):
return '\n\n'.join(str(book) for book in self.books)
def main():
#
# You get to write this part,
# but here are some code examples:
#
lib = Library()
book1 = Book('Fun with Dick and Jane', 'May Hill Arbuthnot', 160, '1951')
lib.add(book1)
book2 = Book('The Adventures of Pinocchio', 'Carlo Collodi', 171, '1911')
lib.add(book2)
# prompt for book 3 information
book3 = Book.from_prompt()
lib.add(book3)
# find a book and display its information
print('='*30)
print(lib.find_title('The Adventures of Pinocchio'))
# display the whole library contents
print('='*30)
print(lib)
if __name__=="__main__":
main()

Categories