StringVar() with Listbox multiple or extended - lists converting to string - python-3.x

I have a tkinter Listbox and I'm using a StringVar().set() to set the values from a list. When I get the values back using StringVar().get(), they are converted to an awkward string format, like this:
"('Item1', 'Item2', 'Item3')"
What's the best way to avoid this conversion in the first place, or failing that, to convert the string back to the initial list?
You can use this snippet of code to reproduce the problem in its most simple form:
import tkinter as tk
root = tk.Tk()
values = tk.StringVar(root)
values.set(['Item1', 'Item2','Item3'])
print(values.get())
It's not pretty, but I had come up with this:
values.get()[2:-2].split("', '")

As StringVar is inherited from Variable with overridden get() function which converts the stored value to string.
Using Variable will not have such conversion.

Related

Extracting boolean values embedded in string in Python

I ran a survey on Mechanical Turk, and the results were returned to me in a string formatted like this:
[{"Q1_option1":{"Option 1":true},"Q1_option2":{"Option 2":false},"Q2_option1":{"Option 1":true},"Q2_option2":{"Option 2":false}}]
I'm not the sharpest programmer out there, and I'm struggling with how to extract the boolean values from the string. I only need the "true" and "false" values in the order they appear.
I would really appreciate any help!
You can use the regular expression module re to extract the values
import re
string = '[{"Q1_option1":{"Option 1":true},"Q1_option2":{"Option 2":false},"Q2_option1":{"Option 1":true},"Q2_option2":{"Option 2":false}}]'
bool_vals = re.findall("true|false", string)
print(bool_vals)
bool_vals is a list that contains the values in the order they appeared in your input string.

How set a standard format specifier to be used throughout a module when using f-strings?

I am using f-strings for formatting strings and injecting variable values into the string, is there a way to set a format-spec for an entire module in python?
I am aware of Standard Format Specifiers which can be used to specify formats for each string, but how do I do it at once for the whole module?
Eg:
f""" Some random string {value1}, some more text {value2:.2f} ... """
Here I am specifying the format for value2, but I want to set a format for all globally.
f"""% profits are {profit}"""
Had I set format spec to {profit:.2f} this will be set to two decimal places, but I want to set that :.2f globally so that number decimal places can be changed with one variable update.
Something like format-spec = ':.2f' and all the f-string injected values should be displayed as floats with two decimals (if its a numbers).
If I understand you correctly, you want to define a string format one time that is usable throughout a script. I would create a function, callable from anywhere in your script that produces the formatted string as shown below:
def create_string(v_str: str, v_num: float) -> str:
return f""" Some random string {v_str}, some more text {v_num:.2f} ... """
You can then use the create_string function from anywhere in your script and produce the desired output as illustrated below:
print(create_string('Some words here', 2.56))
which yields:
Some random string Some words here, some more text 2.56 ...

Python tkinter, label has no attribute 'count'

I have an error message saying:
sentences = text.count(".") + text.count("!") + text.count("?")
AttributeError: 'Label' object has no attribute 'count'
What can I use instead of .count to count items?
Accessing the Label object directly will not get the text of it. You'll need to do text["text"].count or text.cget("text").count. Either will extract the actual text from the label. Tkinter objects can be treated as dictionaries, where the lookup keys are their attributes. cget stands for "configuration get" and allows you to more safely retrieve the attributes.
This occurs because the object text does not implement the function count().
Assuming that the text object you are referring to is a tkinter Label, you need to call count() like this:
text["text"].count(string)
So the line you posted would look like this instead:
sentences = text["text"].count(".") + text["text"].count("!") + text["text"].count("?")
Also, I would recommend you change the variable name text to something else that is more descriptive to avoid confusion in the future.

PySide - How to dynamically update a string value based on QLineEdit Text value?

How do I make my string dynamically updated every time the Text value from a QLineEdit changes? I tried using signals and slots and works fine with QLabel, but not string.
self.lnEditCurrentNS = QtGui.QLineEdit(self) # This is my QLineEdit
my_string = 'none'
self.lnEditCurrentNS.textChanged.connect(self.onSelectedValue)
def onSelectedValue(self):
selectedValue = self.txtEditCurrentNS.displayText()
my_string = selectedValue
Let's say currently lnEditCurrentNS = 'none', then its changed to 'hello'. The value of my_string remains as 'none' instead of getting updated to 'hello'.
The value of lnEditCurrentNS got updated dynamically when the current index of a combobox I have is changed (combobox = 'hello', lnEditCurrentNS = 'hello')
I'm not very familiar with PySide/PyQt so any guidance is highly appreciated. Thanks.
You declared my_string outside the onSelectedValue, you assigned a value inside onSelectedValue. Now if you use my_string outside the onSelectedValue, it won't give the lineEdit's text.
You can do the following trick:
self.my_string = 'None'
...
def onSelectedValue(self):
self.my_string = self.textEditCurrentNS.text()
You can now use self.my_string at any place in the code to have the current text of the lineEdit.

What do empty square brackets after a variable name mean in Groovy?

I'm fairly new to groovy, looking at some existing code, and I see this:
def timestamp = event.timestamp[]
I don't understand what the empty square brackets are doing on this line. Note that the timestamp being def'd here should receive a long value.
In this code, event is defined somewhere else in our huge code base, so I'm not sure what it is. I thought it was a map, but when I wrote some separate test code using this notation on a map, the square brackets result in an empty value being assigned to timestamp. In the code above, however, the brackets are necessary to get correct (non-null) values.
Some quick Googling didn't help much (hard to search on "[]").
EDIT: Turns out event and event.timestamp are both zero.core.groovysupport.GCAccessor objects, and as the answer below says, the [] must be calling getAt() on these objects and returning a value (in this case, a long).
The square brackets will invoke the underlying getAt(Object) method of that object, so that line is probably invoking that one.
I made a small script:
class A {
def getAt(p) {
println "getAt: $p"
p
}
}
def a = new A()
b = a[]
println b.getClass()
And it returned the value passed as a parameter. In this case, an ArrayList. Maybe that timestamp object has some metaprogramming on it. What does def timestamp contains after running the code?
Also check your groovy version.
Empty list, found this. Somewhat related/possibly helpful question here.
Not at a computer, but that looks like it's calling the method event.timestamp and passing an empty list as a parameter.
The same as:
def timestamp = event.timestamp( [] )

Resources