So I am creating a scroll-bar in appJar to show 10 numbers at a time (1-10, 11-20, etc.), and I am wondering what the best way is to go about this.
Should I create a function to hide the next 10 numbers until the scrollbar (which is a scale, though this might be the wrong method), and then they appear?
I am genuinely lost right now, as I've only started learning how to use appJar about 2 days ago for a project. Any ideas would be a great help. Yes, this is just the gui part, and the Python (3.6) has not been added yet, but will be.
from appJar import gui
def press(btn):
if btn == "1":
app.setLabel("answer", "1!")
elif btn == "2":
app.setLabel("answer", "2!")
elif btn == "3":
app.setLabel("answer", "3!")
elif btn == "4":
app.setLabel("answer", "4!")
elif btn == "5":
app.setLabel("answer", "5!")
elif btn == "6":
app.setLabel("answer", "6!")
elif btn == "7":
app.setLabel("answer", "7!")
elif btn == "8":
app.setLabel("answer", "8!")
elif btn == "9":
app.setLabel("answer", "9!")
elif btn == "10":
app.setLabel("answer", "10!")
app.startScrollPane("scroller")
elif btn == "11":
app.setLabel("answer", "11!")
elif btn == "12":
app.setLabel("answer", "12!")
app.stopScrollPane("scroller")
app=gui()
app.setFont(20)
app.addButtons(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], press)
app.addScale("scroller")
app.setScaleChangeFunction("scroller", press)
app.setButton ("1", "1")
app.setButton ("2", "2")
app.setButton ("3", "3")
app.setButton ("4", "4")
app.setButton ("5", "5")
app.setButton ("6", "6")
app.setButton ("7", "7")
app.setButton ("8", "8")
app.setButton ("9", "9")
app.setButton ("10", "10")
app.setButton ("11", "11")
app.setButton ("12", "12")
app.addLabel ("answer", "Pick a Number!")
app.go()
I see two alternatives here:
Create a scrollPane, and utilise the scrollPane's built in scrollbars
Link the Scale widget to a function that updates the labels of the buttons
It really depends on how you want the GUI to look...
For option 1, try the following, instead of the scale:
app.startScrollPane("p1")
for i in range(1,101):
app.addButton(str(i), press, 0, i)
app.stopScrollPane()
For option 2, get rid of the list of setButton() calls, and replace them with a call to a new function: updateButtons().
Then, in that function, have something like:
def updateButtons(btn=None):
m = app.getScale("scroller") * 10
for i in range(1, 13):
app.setButton (str(i), str(m+i))
You'll also probably want to set the range on the scale: app.setScaleRange("scroller", 0, 9)
And, register the scale to call the updateButtons() function, instead of press
You'll also need to do the equivalent maths for the button presses, as they return their ID, not their value.
Related
I'm racking my brain on this and I'm sure it's unnecessary. I've tried looking for the answer online but it's leading me nowhere.
I'm writing a simple menu script (probably not the nicest format). In prompt 2, 3, 4 I'm in need of an option to get back to the previous prompt. Based on what I've found I just keep looping myself into a bigger and bigger issue.
Here is what I have:
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_cluster = 'Outdoors'
elif user_input2 == "2":
user_selected_cluster = 'Gym'
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
print("Invalid option selected. Run script again.")
exit()
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_cluster = 'AM'
elif user_input4 == "2":
user_selected_cluster = 'PM'
else:
print("Invalid option selected. Run script again.")
exit()
I've tried a variety of while loops and even turning these into functions, which to be honest, I don't have a complete grasp of.
Every solution has just ended up with me looping the prompt I'm on, looping the entire script, or ending the script after prompt_1
Honestly would prefer to learn it instead of someone doing it but I can't even find good videos that address the subject.
Python (like many other languages) does not have a go to option.
The "goto" statement, which allows for unconditional jumps in program flow, was considered to be a bad programming practice because it can lead to confusing and difficult-to-maintain code. Instead, Python uses structured control flow statements, such as if, for, and while loops, which encourage clear and organized code that is easy to understand and debug.
However, you can put the code into functions to achieve the same result, like this:
def main():
''' the main module '''
# have 3 attempts at each question, then move on.
for i in range(3):
x = action_01()
if x != 'invalid': break
for i in range(3):
x = action_02()
if x != 'invalid': break
for i in range(3):
x = action_03()
if x != 'invalid': break
for i in range(3):
x = action_04()
if x != 'invalid': break
def action_01():
print("\nPlease select an action:")
print("\n1. Run")
print("2. Swim")
user_input1 = input("\nPlease make your selection: ")
if user_input1 == "1":
user_selected_action = "run"
elif user_input1 == "2":
user_selected_action = "swim"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_02():
print("\nPlease select an environment:")
print("\n1. Outdoors")
print("2. In a Gym")
user_input2 = input("\nPlease make your selection: ")
if user_input2 == "1":
user_selected_action = 'Outdoors'
elif user_input2 == "2":
user_selected_action = 'Gym'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_03():
print("\nPlease select an day:")
print("\n1. Saturday")
print("2. Sunday")
user_input3 = input("\nPlease make your selection: ")
if user_input3 == "1":
user_selected_action = "Sat"
elif user_input3 == "2":
user_selected_action = "Sun"
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
def action_04():
print("\nPlease select a time of day:")
print("\n1. Day")
print("2. Night")
user_input4 = input("\nPlease make your selection: ")
if user_input4 == "1":
user_selected_action = 'AM'
elif user_input4 == "2":
user_selected_action = 'PM'
else:
user_selected_action = "invalid"
print("Invalid option selected. Run script again.")
return user_selected_action
if __name__ == '__main__':
main()
Note, there are even more efficient ways, but this will be a good starting point for you.
I have a list of chunk objects that I would like to iterate through and sort into lists where all chunk elements have the same name.
I wrote this:
zero,one,two,three,four,five,six,seven = [],[],[],[],[],[],[],[]
for chunk in self.chunk_collection:
if chunk.chunk_name == "0":
zero.append(chunk)
if chunk.chunk_name == "1":
one.append(chunk)
if chunk.chunk_name == "2":
two.append(chunk)
if chunk.chunk_name == "3":
three.append(chunk)
if chunk.chunk_name == "4":
four.append(chunk)
if chunk.chunk_name == "5":
five.append(chunk)
if chunk.chunk_name == "6":
six.append(chunk)
if chunk.chunk_name == "7":
seven.appned(chunk)
Which allows me to iterate through the chunk_collection once, but this doesn't scale well at all.
What if there are n lists I would like to sort the contents of chunk_collection into!
Is there a better way to write this code or is there a pattern that I should implement so I don't have to come across this problem at all?
I try to increase the quality of this code, because Sonarqube doesn't like when there is too much if/elif.
I tried to use "swich case"; but this function is too young for my production environment.
Can i use dictionnary method with 2 conditions ?
This is my code :
if letter == "ABC" and orientation == "south" :
numero = "1"
elif letter == "ABC" and orientation == "east" :
numero = "2"
elif letter == "EDF" and orientation == "south" :
numero = "3"
elif letter == "EDF" and orientation == "east" :
numero = "4"
elif letter == "GHI" and orientation == "south" :
numero = "5"
elif letter == "GHI" and orientation == "north" :
numero = "6"
elif letter == "GHI" and orientation == "east" :
numero = "7"
You can create a mapping between letter, orientation and number and then fetch number from there:
values = {
("ABC", "south"): "1",
("ABC", "east"): "2",
("EDF", "south"): "3",
("EDF", "east"): "4",
("GHI", "south"): "5",
("GHI", "north"): "6",
("GHI", "east"): "7",
}
letter = "GHI"
orientation = "north"
number = values[(letter, orientation)]
If letter and orientation can have invalid values, make sure to enclose the number access in a try/except block:
try:
number = values[(letter, orientation)]
except KeyError as e:
print(f"No number defined for: {e}")
BREAK DOWN OF PROJECT
The user is asked to enter a number and a second number.
a variable named results is created by adding the two numbers
together.
We search for the results in the 1st if statement in a dictionary
named ans (short for answers).
This part functions as it should. It than gives those results back
to the user by displaying the original numerical equation. And a
version of the equation using letters (see full code below if you
are confused).
However if the results do not match the 1st if statement it moves to the next. Before the whole if statement a variable named search is created by:
search = tuple(str(results))
I need to now take the results and search each individual character and see if those characters also appear in the dictionary (ans). However, it's not searching for the tuple character strings in the dictionary.
FULL CODE
translate_results = {
1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H",
9: "I", 10: "J", 20: "T", 0: 0, "1": "A", "2": "B", "3": "C", "4": "D",
"5": "E", "6": "F", "7": "G", "8": "H", "9": "I", "0": "0",
}
ans = translate_results
user = input('Enter a number: ')
user2 = input('Enter another number: ')
results = int(user) + int(user2)
search = tuple(str(results))
if results in ans:
print(f"{user} + {user2} = {results}")
print(f"{ans[user]} + {ans[user2]} = {ans[results]}")
elif search in ans:
print(f"{user} + {user2} = {results}")
print(f"{ans[user]} + {ans[user2]} = {ans[search]}")
print(search)
else:
print(f" Answer is {results}")
print(f"However, elif statment failed. Tuple list created: {search}")
Example One
So if the user types in 1 (user) and 3 (user2) the output is:
1 + 2 = 3
A + B = C
Based on the 1st if statement.
Part 2 If Statement
This is suppose to activate when it finds the individual string characters from search (variable) in the dictionary (ans). Than it is suppose to take those characters match them in the dictionary and display the dictionary values instead.
Example Two (if it worked)
So the user enters 1 (user) and 29 (user2) the out put would be after matching variable search to ans:
1 + 29 = 30
A + BI = C0
something like this?
translate_results = {
1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H",
9: "I", 10: "J", 20: "T", 0: 0, "1": "A", "2": "B", "3": "C", "4": "D",
"5": "E", "6": "F", "7": "G", "8": "H", "9": "I", "0": "0",
}
ans = translate_results
user = input('Enter a number: ')
user2 = input('Enter another number: ')
results = int(user) + int(user2)
search = tuple(str(results))
if results in ans:
print(f"{user} + {user2} = {results}")
print(f"{ans[user]} + {ans[user2]} = {ans[results]}")
elif set(search).issubset(set(ans.keys())):
txt1= '' #for each create a string where the program appends the translated values
for i in user:
txt1+=str(ans[i])
txt2= ''
for i in user2:
txt2+=str(ans[i])
txtres= ''
for i in search:
txtres+=str(ans[i])
print(f"{user} + {user2} = {results}")
print(f"{txt1} + {txt2} = {txtres}")
print(search)
else:
print(f" Answer is {results}")
print(f"However, elif statment failed. Tuple list created: {search}")
inputs:
10, 15
output:
10 + 15 = 25
A0 + AE = BE
('2', '5')
also check the translate() function, if that can help.
print("Descriptive Analytics:\n\t*1. Summary\n\t*2. Time Series\n\t*3.
Trend Lines\n\t*4. Moving Averages\nPredictive Analytics:\n\t*5.Linear
Regression Model\n\t*6.Non Linear Regression Model")
while True:
try:
choice = (input("Step 2: Please choose an option:"))
except ValueError:
print("Sorry, you've entered an invalid input. Please try again!")
if choice in ("1","2","3","4","5","6"):
break
if choice == "1":
print("Descriptive Analytics: Summary")
elif choice == "2":
print("Descriptive Analytics: Time Series")
elif choice == "3":
print("Descriptive Analytics: Trend Lines")
elif choice == "4":
print("Descriptive Analytics: Moving Averages")
elif choice == "5":
print("Predictive Analytics: Linear Regression Model")
elif choice == "6":
print("Predictive Analytics: Non Linear Regression Model")
Can anyone spot the error in this code? So far, the loop works effectively but fails to print the line "Sorry, you've entered an invalid input. Please try again!
You need to use proper indentation level and make sure your code is executed in else block, not except block,
while True:
try:
choice = (input("Step 2: Please choose an option:"))
except ValueError:
print("Sorry, you've entered an invalid input. Please try again!")
else:
if choice == "1":
print("Descriptive Analytics: Summary")
elif choice == "2":
print("Descriptive Analytics: Time Series")
elif choice == "3":
print("Descriptive Analytics: Trend Lines")
elif choice == "4":
print("Descriptive Analytics: Moving Averages")
elif choice == "5":
print("Predictive Analytics: Linear Regression Model")
elif choice == "6":
print("Predictive Analytics: Non Linear Regression Model")
if choice in ("1", "2", "3", "4", "5", "6"):
break