Populate wxChoice at Start of Program Run | Python - python

As soon as my program is run, I want my wxChoice to be populated with items from a list I designate. I am using wxFormBuilder to handle the GUI elements of my program.
My code:
def onDropDownSelection(self, parent):
#Open designated file
lines = tuple(open("/Users/it/Desktop/Classbook/masterClassList.txt", 'r'))
#Strips the first line of the file, splits the elements, assigns to "one"
lines[1].rstrip()
one = lines[1].split("|")
#My attempt to populate the wxChoice with my list "one"
self.firstChoice.SetItems(one)
This event is activated when the user clicks on the drop-down (wxChoice) menu, and re-populates every time it is clicked on.
Is there a way I can populate my wxChoice, only once, upon the initial opening/running of the program?
I have placed this code where the wxChoice is being created. However, I am now experiencing a "Unindent does not match any outer indentation level" on line 44. How do I fix this?

Check for your indentation. Some times if you copy paste, this can mess things up.
Just rewrite it or replace it with another statement. See here:
IndentationError: unindent does not match any outer indentation level
Problem is if you make your indentation with tabs and then copy-paste some code from an example page, where the indentation is made with spaces. Then you have mixed Indentations. I've had these a lot of times.

Related

Try-Except in the For loop

I written the below Try-Except code in a For Loop for Python - PostgreSQL database input.
I have a list in .csv file to input into the PostgreSQL database.
1 of the column is primary data enabled.
Hence, if the data in the list is duplicated, the Python will throw error.
I written below code and my imagination is the code will run "try" 1st, if "try" error then only jump to the "except" line, for every rows in the list (loop).
But, when I execute my code, once the program go to "except" line, then the program would not go to "try" line again.
Ex.
If my list of data all fresh, the program run and input all rows to database correctly.
If my duplicated data is in the 1st line of the list, the program run to "except" line and the fresh data at the bottom are not input to the database.
As long as there is duplicated data on top, the program will just run into "except" line without go back to "try" line.
Any idea how to improve my code here? Thank you.
My intention is all fresh data need to capture into the database, while there is duplicated, the data row shall be skipped and continue for next line.
for data in df.iterrows():
vreceivingdate = str(data[1][0])
vreceivingtime = str(data[1][1])
vscanresult = str(data[1][2])
vinvoicenbr = str(vscanresult[0:6])
vlotnbr = str(vscanresult[6:9])
vcasenbr = str(vscanresult[9:12])
try:
rec.insertRec(vreceivingdate, vreceivingtime, vscanresult, vinvoicenbr, vlotnbr, vcasenbr)
except:
dupDataCounter += 1
Finally I found the solution for my question.
I shall not use Try-Except for this case.
To do what I want to do should use the PostgreSQL function:
"ON CONFLICT DO NOTHING".

VS Code for Python entering a new line when function call is long

I have a long time problem and it got me angry, so I will ask here. When I have a long function call in VS Code, it automatically enteres a new line somewhere in the parametres.
I have this on one line:
dict_file = os.path.join(path_converted,
'dictionary_'+filename+'.picklelongtestlongtestlongtestlongtestlongtest')
and it adds newLine behind "(path_converted, 'dictionary_' +" and the rest is written on the new line with some indention.
I have pretty big monitor, so I do not want to end these lines so early. Could I somehow turn it off in Settings? I am using FormatOnSave and it is pretty anoying.
Thank you for all answers :))
Andrew
There're the following two settings in VS Code:
"editor.wordWrap": Controls how lines should wrap.
"editor.wordWrapColumn": Controls the wrapping column of the editor when #editor.wordWrap# is wordWrapColumn or bounded.
So there're two solutions to your question, writing it in Settings.json:
Turn off the wordWrap:
"editor.wordWrap":"off",
Still keep wordWrap on but changing the code's max-length:
"editor.wordWrap": "wordWrapColumn",
"editor.wordWrapColumn":130,

How to refresh or update frame after value changes in text file using Python/Tkinter

So basically I am reading a valuefrom a text file which is displayed on the Profile frame using a label.
def view_value(self):
self.user = self.controller.user
self.view_value()
with open(self.user + '.txt', "r") as f:
value_line = 2
for i, line in enumerate(f):
if i == value_line:
self.value.set(line)
self.value.config(textvariable=line)
When I go to a different frame to calculate this value again, it will update the text file with the newly calculated value. However, when I go back to the previous page using the back button - the old value is still there. To get the new value to appear I need to reopen/re-run the program.
Is it possible to have the newly updated value displayed on the page without restarting the application? I have tried calling my view_value method to try and update the value and also tried configuring the label from the other class but wasn't able to get it working.
I also realise there are probably a million things wrong with my code, I am very new to Python so apologies!
You need to update the StringVar Profile.allowance in order to make the display in Profile page updated. The simple way is adding the following statement before self.controller.show_frame(Profile) in write_to_file() of CalculateAllowance class:
self.controller.frames[Profile].allowance.set(self.user_data[2])
Also you need to fix the following issues in your code:
Remove calling self.view_allowance() inside view_allowance() in Profile class as it will cause infinite recursion problem.
Remove self.holiday_allowance_amount.config(textvariable=line) in view_allowance() as it wrongly reassigns textvariable to a string.

Editing every 3rd line of file in vim

I was making a templated list of methods in vim for a python project. I added lines between each method and wanted to add a pass to each method for now-until I implement the method, this will still be interpretable python code. In vim I know how to edit spatially contiguous lines of a file using :10,17s/<search regex>/<substitute>/ but after doing my edits to add empty lines between methods, I needed to insert the a pass every 3rd line. The way I found to do this used pipes and & via:
:10s/<search regex>/<substitute>|13&|16& etc. I had maybe 15 of the ampersands chained together to get this to work. Is there a more succint way to get this behaviour in vim?
To address comment, here is a minimal example, in the file myfile.py I have:
def _fun1(self):
def _fun2(self):
def _fun3(self):
def _fun4(self):
...etc
On the 2nd line, the 5th line, the 8th line, etc. I want to insert pass (w/4 spaces before to keep consistent spacings), /i have this up to _fun15(self): so would like to get the behavior w/o 14 |lineNo&s chained together. Perhaps an incrementing feature w/a variable for the line numbers or some other code that creates the behavior.
Here is one possible way:
:g/def _fun/normal! opass
On each line matching def _fun…
open a new line below…
and insert pass.
If you want to have one single line between each stub:
:g/def _fun/normal! opass^OJ^Ox
On each line matching def _fun…
open a new line below…
insert pass…
leave insert mode for a single command…
join the line below with the current line…
leave insert mode for a single command…
and remove that pesky <Space>.
Record a macro
qajopass<Esc>jq
Now execute it by running #a (next time you can use ##).
As #midor said it can be then used with :g command in form of:
:g/def _fun\d\+/norm #a
To execute this macro on all matching lines.
To put 'pass' with indentation below each function definition I would use:
:g/^def/put =' pass'
^ ........... begining of each line
put ......... puts contents bellow
To squeeze blank lines:
:g/^$/,/./-1j
a global command the gets from each empty line ^$
until next non-empty line minus one, performs a join command

Python - Deleting a line from a file (To-Do List program that uses entries, different from other posts)

I have a problem with my code. I am trying to delete a specific line from a file. I am making a To-Do List program in Tkinter, and I am using a Label as the to-do list. I have two buttons, 'Add Item' and 'Delete Item'. I also have an entry box, and the buttons take the string from the entry using the .get() method. The delete button is not working because I cannot find a way to delete a line from a file that the program is using to store the list. I have looked over many other posts about the same problem, but mine is different. Whenever I run the program, and I click delete item after I fill out the text box, it deletes ALL items from the file, but I only want it to delete one item. The problem is NOT the one that #JetMashKangaroo had in this post: How to delete a line from a file in Python.
Here is the snippet of code:
def dele():
global ItemName
global Display
global List
ToDoDel = ItemName.get()
new_f = List.readlines()
List.seek(0)
for line in new_f:
if ToDoDel not in line:
List.write(line)
List.truncate()
Display['text'] = List.readlines()
ItemName is the entry box. Display is the label that displays the To-Do list. List is the variable below:
List = open('***/***/To-Do_List.txt','r+')
The program works perfectly, but I cannot add this delete function because it deletes all the text from the file. the function dele is called when the button 'Delete Item' is pressed. Help would be greatly appreciated.
The most likely reason you're running into a problem is that you are attempting to modify the list while also iterating over it. Here's an example post of someone else who ran into a similar issue.
My suggestion is that you keep track of which indexes to modify within your loop, then remove them after the loop has completed.

Categories