I created a combobox to show a list of values out of a sqlite database.
If I sent the values to the combobox, the list will shown. The problem is, that the field will not filled with the first value and stay empty until I select on item of out of the drop menu.
Could I set a value to be displayed directly?
Here my code snippet:
self.e_business = ttk.Combobox(address_frame, width = 40)
self.e_business.grid(row=3, column=1, columnspan=2, padx=(5,20), pady=(15,5), sticky='WE')
The function which send the values:
def show_name_search(self, event):
...
widget = event.widget
selection = widget.curselection()
indName = widget.get(selection[0])
print(indName)
print("selktierter Wert: {}".format(indName))
self.realName.set(indName)
connection = sqlite3.connect(select_connect_db)
print('Database connected.')
with connection:
cursor = connection.cursor()
cursor.execute("SELECT number, type, prio, id, uniqueid FROM numbers WHERE realName='"+indName+"';")
data = cursor.fetchall()
print(data)
cache = []
for row in data:
cache.append(row[0])
self.e_business['values'] = cache
The cache list looks like:
CACHE: ['081191310912', '071109131090', '01754123353']
Define the list in the __init__() and then populate inside the function, like:
def __init__(self):
self.cache = []
... # Rest of codes
def show_name_search(self,event):
....# Rest of codes
for row in data:
self.cache.append(row[0])
self.e_business['values'] = self.cache # Set the value to the new list
self.e_business.current(0) # Set the first item of the list as current item
To set the item to the current item, you can use current() and the index of the item to be set first. Note that the indentation levels will change according to your class.
Related
Can someone please help me?
All I want to do is update a field in a table, lets say for example membership number if it meets certain conditions.
For example: I have a list of membership numbers. IF the numbers on the list match the membership number in the table - we don't do anything.
If it doesn't match - then we change the membership number to another number that is stored in my input CSV. (i know this sounds back to front, but this is just an analogy)
So in essence I am asking - how do you update a field in a database table? This doesn't seem to be working:
def stream inputStream.
def stream outStream.
def var abcData as char extent 4 no-undo.
def var vl-XYZ# as integer.
def var vl-link# as integer.
def var vl-orig-ABC# as char.
def var vl-new-ABC# as char.
/* def var vl-error as char. */
def var vl-match as char.
def var vl-status as char.
def buffer bMembers for members.
input stream inputStream from "/home/abc.csv".
output stream outStream to "/home/xyz.csv".
export stream outStream delimiter "'" "ABCID" "Match".
repeat:
assign
abcData = "".
import stream inputStream delimiter "'" abcData.
assign
vl-link# = integer(abcdata[1])
vl-XYZ# = integer(abcData[2])
vl-orig-ABC# = string(abcData[3])
vl-new-ABC# = string(abcData[4]) .
for each account no-lock where account.link# = vl-link#,
First members no-lock where members.XYZ# = vl-XYZ#:
if members.abc# = vl-orig-ABC# then
assign
vl-status = "Needs amending".
if members.abc# <> vl-orig-ABC# then
assign
vl-status = "No action needed"
members.abc# = vl-new-ABC#.
export stream outStream delimiter "'" vl-link# vl-XYZ# vl-orig-ABC# members.abc# vl-status
]
The problem with updating the members records will be in the FOR EACH. You need to use EXCLUSIVE-LOCK with the members table to be able to update records.
for each account no-lock where account.link# = vl-link#,
First members EXCLUSIVE-LOCK where members.XYZ# = vl-XYZ#:
The selection criteria for the members table does also not seem to be right, in a joined FOR EACH statement, the second table should depend on the first one like
for each account no-lock where account.link# = vl-link#,
First members EXCLUSIVE-LOCK where members.<somefield of members> = account.<matchine ield in account>
AND members.XYZ# = vl-XYZ#:
I have checked a few of the posts having the same issue and it tells me how to do it but it is not working.
My code:
class Product:
def __init__(self,price,prod_id,quantity):
self.price = price
self.prod_id = prod_id
self.quantity = quantity
self.shop_inventory = {}
self.amount = {}
class Inventory(Product):
def update_stock(self):
self.shop_inventory[self.prod_id] = self.quantity
self.amount[self.prod_id] = self.price
def return_stock_item(self):
look_up = input("What item would you like to check? ")
item = self.shop_inventory[look_up.lower()]
price = self.amount[look_up.lower()]
return f"{look_up.capitalize()}: There are {item} in stock and cost ${price} each."
def display_stock(self):
return self.amount.items()
To set the values Ive been using
stock = Inventory(2.34,'apple',5)
stock.update_stock()
It's part of a class and everything else in the class is working right. Just this one function is not working. I have tried this method as well as the update() method and neither are adding new key values. It is only over writing the same first spot. I have an item check in the class for all the dictionary items and it always only returns one [key][value] no matter how many times I change the key name.
Thank you for any help.
I am working on a fantasy football type app for a school project.
We have created a scrollview with a list of characters in a team within it, each assigned to a button. on press of the button a new scrollview displaying a second list of 'inactive character buttons' is displayed, allowing the user to press one to swap the first and second character from team to team.
our issue comes from a difficulty in managing to 'locate' which button is pressed in order to tell our swap function which two characters to swap on the list. Is it possible to retain the id of a button and call it into a new function on press of said button?
Our code is a bit messy, but is displayed bellow:
class SMApp(App):
teamlist = []
idvar = ""
btnlist = []
def popupfunc(self, event):
"""
creates a popup asking if the user wishes to swap a character from team to subs
then proceeds to allow user to choose who swaps
"""
def subscroll(self):
"""
opens scroll list of substitute characters in a popup
"""
sublist = []
curs.execute('SELECT * FROM Subs')
for row in curs:
sublist.append([row[0], row[2]])
layout = GridLayout(cols=2, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
for i in range(len(sublist)):
btn = Button(text=str(sublist[i][0]), size_hint_y=None, height=40)
layout.add_widget(btn)
lbl = Label(text=str(sublist[i][1]), size_hinty=None, height=40)
layout.add_widget(lbl)
root = ScrollView(size_hint=(None, None), size=(400, 400))
root.add_widget(layout)
popup2 = Popup(content=root, size=(7, 10), size_hint=(0.55, 0.8), title="list of subs")
popup2.open()
box = BoxLayout()
btn1 = Button(text='yeah ok')
btn2 = Button(text='nope')
popup1 = Popup(content=box, size=(10, 10), size_hint=(0.3, 0.3), title="add to team?")
btn2.bind(on_press=popup1.dismiss)
btn1.bind(on_press=subscroll)
box.add_widget(btn1)
box.add_widget(btn2)
popup1.open()
def build(self):
curs.execute('SELECT * FROM Team')
for row in curs:
self.teamlist.append([row[0], row[2]])
layout = GridLayout(cols=2, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
for i in range(len(self.teamlist)):
btn = Button(text=str(self.teamlist[i][0]), size_hint_y=None, height=40, id=str(i))
btn.bind(on_press=self.popupfunc)
self.btnlist.append(btn)
layout.add_widget(btn)
lbl = Label(text=str(self.teamlist[i][1]), size_hinty=None, height=40)
layout.add_widget(lbl)
for item in self.btnlist:
print item.id
root = ScrollView(size_hint=(None, None), size=(400, 400),
pos_hint={'center_x':.5, 'center_y':.5})
root.add_widget(layout)
return root
if __name__ == '__main__':
SMApp().run()
Each of the btn = Button(...) you create is a different object, therefore you can tell which is pressed. The thing is what way you'll choose.
You can use:
str(your button) and get a specific object address(?) like 0xAABBCCEE
bad, don't do that
Button(id='something', ...)
ids from kv language
or create own widget with a property for specific identificator. Then you'd use a loop for the parent's children which would check for identificator and do something:
for child in layout.children:
if child.id == 'something':
# do something
And it seems you'd need this loop inside your subscroll, or access that layout some other way.
I need to select a particular row in a table with selenium web driver, I have close to 5000 rows, Navigating through each row would be difficult. Any better approach if we have?
You need to click on a checkbox to select the row right?
I'll assume thats what you meant:
The only way I know how is to check each row, select the filter (i.e. a customer number) and once you find it, click on the selection checkbox.
Mostly of the tables are similar so here is an example:
This is your table:
= = = = = = =
=================================================================================================
= = = = = = =
=================================================================================================
= = = = = = =
=================================================================================================
Lets say that in the first row, is where the checkbox is, and that in the second row is the location of the filter.
meaning the data you will use in order to know that this is the row you need....
you will need to inspect the table element in order to find its ID, once you have that info you can use a similar method as the below:
Where you will use your webdriver, data filter, tableID and the number of the column where your data filter is located.
The method will return the row you need to click, then you can simply use the row[columnNumberLocation].Click() in order to select it.
public IWebElement returnRow(IWebDriver webDriver, string filter ,string tableName, int i)
{
IWebElement tableElement = webDriver.FindElement(By.Id(tableName));
IWebElement tbodyElement = tableElement.FindElement(By.TagName("TBODY"));
List<IWebElement> rows = new List<IWebElement>(tbodyElement.FindElements(By.TagName("tr")));
foreach (var row in rows)
{
List<IWebElement> cells = new List<IWebElement>(row.FindElements(By.TagName("td")));
if (cells.Count > 0)
{
string s = cells[i].Text;
if (s.Equals(filter))
{
return row;
}
}
}
return null;
}
It depends on what is your requirement of selecting that particular row.
I assume you need to select that according to the row index.
So it's all about the your x-path to locate the element.
ex: I need to get row number 2000
WebElement element = driver.findElement(By.xpath("//tr[2000]"));
I'd like to build a hex editor-like view using a QTableView. Each cell will be the representation of a byte of data. How can I configure the QTableView selection behaviour such that it acts like a typical text edit control? That is, rather than selecting a rectangular region of cells, it should select the remaining cells on a line, the entire contents of any intermediate lines, and partial contents on the final line.
In diagram form (x is selected, . is unselected), I want this:
..................
......xxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxx......
..................
I do not want this:
..................
......xxxxxx......
......xxxxxx......
......xxxxxx......
......xxxxxx......
..................
Ultimately, I had success changing the default behaviour of the QItemSelectionModel by subclassing it and overriding the select method, as described here: https://stackoverflow.com/a/10920294/87207
Here's the key part of my code:
class RollingItemSelectionModel(QItemSelectionModel):
def qindex2index(self, index):
""" convert QModelIndex to offset into buffer """
m = self.model()
return (m.columnCount() * index.row()) + index.column()
def index2qindex(self, index):
""" convert offset into buffer into QModelIndex """
m = self.model()
r = index // m.columnCount()
c = index % m.columnCount()
return m.index(r, c)
def select(self, selection, selectionFlags):
# PyQt5 doesn't have method overloading, so we type switch
if isinstance(selection, QItemSelection):
# This is the overload with the QItemSelection passed to arg 0
qindexes = selection.indexes()
indices = []
for qindex in qindexes:
indices.append(self.qindex2index(qindex))
if indices:
low = min(indices)
high = max(indices)
selection = QItemSelection()
for i in xrange(low, high):
qi = self.index2qindex(i)
# inefficient, but functional
# manually add all the bytes to select, one-by-one
selection.select(qi, qi)
elif isinstance(selection, QModelIndex):
# This is the overload with the QModelIndex passed to arg 0
# since it's a single index, already works as expected.
pass
else: # Just in case
raise RuntimeError("Unexpected type for arg 0: '%s'" % type(selection))
# Fall through. Select as normal
super(RollingItemSelectionModel, self).select(selection, SelectionFlags)
I think you can use the QItemSelection/QItemSelectionRange class for this purpose.
Create a new item selection model:
QItemSelectionModel::select( ... )
Then pass it to the view:
QAbstractItemView::setSelectionModel( ... )