Insert text in sg.Multiline from external Keyboard - input

Dears,
I'm wondering if there is a way to Insert text in sg.Multiline from external Keyboard ( Virtual On-Screen Keyboard):
it's working for sg.Input :
if isinstance(element, sg.Input):
if element.widget.select_present():
element.widget.delete(sg.tk.SEL_FIRST, sg.tk.SEL_LAST)
element.widget.insert(sg.tk.INSERT, event)
And not the case with sg.Multiline:
if isinstance(element, sg.Multiline):
if element.widget.select_present():
element.widget.delete(sg.tk.SEL_FIRST, sg.tk.SEL_LAST)
element.widget.insert(sg.tk.INSERT, event)
I got the following error message : AttributeError: 'Text' object has no attribute 'select_present'
The Remaining Issue :
The above issue is fixed and once I want to delete characters from "sg.Multiline" it's going directly to "except" part , below is the script used. Could you please advice ?
elif event == "DEL" :
try:
element = window.find_element_with_focus()
if element.widget.tag_ranges("sel"):
element.widget.delete(sg.tk.SEL_FIRST, sg.tk.SEL_LAST)
else:
insert = element.widget.index(sg.tk.INSERT)
if insert > 0:
element.widget.delete(insert-1, insert)
except:
sg.popup("Error")
Thanks in advance

Related

How to use mapFieldType with gdal.VectorTranslate

I'm trying to export a postgresql database into a .gpkg file, but some of my fields are lists, and ogr2ogr send me the message :
Warning 1: The output driver does not natively support StringList type for field my_field_name. Misconversion can happen. -mapFieldType can be used to control field type conversion.
But, as in the documentation, -mapFieldType is not a -lco, i don't find how to use it with the python version of gdal.VectorTranslate
here ma config :
gdal_conn = gdal.OpenEx(f"PG:service={my_pgsql_service}", gdal.OF_VECTOR)
gdal.VectorTranslate("path_to_my_file.gpkg"), gdal_conn,
SQLStatement=my_sql_query,
layerName=my_mayer_name,
format="GPKG",
accessMode='append',
)
so i've tried to add it in the -lco :
layerCreationOptions=["-mapFieldType StringList=String"]
but it didn't work
so i diged into the code of gdal, added a field mapFieldType=None into the VectorTranslateOptions function, and added into its code the following lines :
if mapFieldType is not None:
mapField_str = ''
i = 0
for k, v in mapFieldType.items():
i += 1
mapField_str += f"{k}={v}" if i == len(mapFieldType) else f"{k}={v},"
new_options += ['-mapFieldType', mapField_str]
And it worked, but is there an other way ?
And if not, where can i propose this feature ?
Thank you for your help

Pysimplegui and Pygame merge

hi I am trying to merge a pygame program with pysimplegui.
i'm looking for a way of grabbing the downstroke of a keyboard key. at the moment i can only see an upstroke of the key no matter what im doing.
I have sucessfully created pysimplegui programs but this is the first time i'm trying to merge with pygame.
window is setup by
window = sg.Window('UNICHALL V2.0',
Win_layout,
border_depth =20,
resizable = True,
keep_on_top = False,
finalize=True,
return_keyboard_events=True,
use_default_focus=False)
and in my pygame program i use
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
stop = pygame.time.get_ticks()
delta = stop - start
key = event.key
if key == 27:
sys.exit(1) ...
i can't get these two work in harmony, they either internally loop forever or simply stop the program dead.
Any help appreciated.
If you just need to detect when key pressed and released, try to bind the event '<KeyPress>' and '<KeyRelease>', not set option return_keyboard_events=True of sg.Window.
Example Code
import PySimpleGUI as sg
layout = [
[sg.InputText('', key='-INPUT-')],
[sg.Button('Add Binding'), sg.Button('Remove Binding')],
]
window = sg.Window('Test Program', layout, finalize=True)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event in ('Press', 'Release'):
e = window.user_bind_event
action = 'pressed' if event == 'Press' else 'released'
print(f'char:{repr(e.char)} | keycode:{e.keycode} | keysym:{e.keysym} | keysym_num:{e.keysym_num} {action}')
elif event == 'Add Binding':
window.bind("<KeyPress>", "Press")
window.bind("<KeyRelease>", "Release")
elif event == 'Remove Binding':
window.TKroot.unbind("<KeyPress>")
window.user_bind_dict.pop("<KeyPress>", None)
window.TKroot.unbind("<KeyRelease>")
window.user_bind_dict.pop("<KeyRelease>", None)
window.close()

How to confirm if user has pressed on a button in pysimplegui

I want the Predict Risk button to work only if one of the above buttons have been pressed before.
The code for the ui is as follows:
layout=[[sg.Text('Choose the Industry')],
[sg.Button("Automobile"),sg.Button("Chemical"),sg.Button("Engineering/Consulting"),
sg.Button("FMCG"),sg.Button("Healthcare/Hospitality"),sg.Button("Infrastructue")],
[sg.Button("IT/Comm/DC"),sg.Button("Manufacturing"),sg.Button("Mines"),
sg.Button("Energy/Oil & Gas"),sg.Button("Pharma"),sg.Button("Retail"),sg.Button("Cement")],
[sg.Text(size=(50,1),key=('loaded'))],
[sg.Text('Enter Observation/Recommendation: ', size =(26, 1)), sg.InputText()],
[sg.Button("Predict Risk")],
[sg.Text(size=(30,1),key=('output'))],
[sg.Text('If the above prediction is correct select \'yes\' else select the correct risk.')],
[sg.Button("Yes"),sg.Button("Low"),sg.Button("Medium")],
#[sg.Text('Select the correct risk: '),sg.Button("Low"),sg.Button("Medium")],
[sg.Text(size=(30,2),key=('trained'))],
[sg.Button("Exit"),sg.Button("Clear Fields")]
]
window=sg.Window("Risk Predictor",layout)
while True:
event, values = window.read()
#obs=values[0]
# End program if user closes window or
if event == sg.WIN_CLOSED or event == 'Exit':
break
window.close()
The above code is not complete.
I want the rest of application to be active only when the one of the top buttons has been pressed.
Secondly is there a way to map the enter key with Predict Risk button so user can just hit enter and get the prediction.
You can use variables or attribute button.metadata to record the state clicked for buttons. Initial value for each button is set by option metadata=False in sg.Button means not yet clicked. When button clicked, button.metadata will be set to True, it means this button clicked.
Here show the way to record the clicked state in button.metadata.
import PySimpleGUI as sg
items = [
"Automobile", "Chemical", "Engineering/Consulting", "FMCG",
"Healthcare/Hospitality", "Infrastructue", "IT/Comm/DC", "Manufacturing",
"Mines", "Energy/Oil & Gas", "Pharma", "Retail", "Cement",
]
length = len(items)
size = (max(map(len, items)), 1)
sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 11))
column_layout = []
line = []
num = 4
for i, item in enumerate(items):
line.append(sg.Button(item, size=size, metadata=False))
if i%num == num-1 or i==length-1:
column_layout.append(line)
line = []
layout = [
[sg.Text('Choose the Industry')],
[sg.Column(column_layout)],
[sg.Text(size=(50,1),key=('loaded'))],
[sg.Text('Enter Observation/Recommendation: ', size =(26, 1)), sg.InputText()],
[sg.Button("Predict Risk", bind_return_key=True)],
[sg.Text(size=(30,1),key=('output'))],
[sg.Text('If the above prediction is correct select \'yes\' else select the correct risk.')],
[sg.Button("Yes"),sg.Button("Low"),sg.Button("Medium")],
[sg.Text(size=(30,2),key=('trained'))],
[sg.Button("Exit"),sg.Button("Clear Fields")]
]
window=sg.Window("Risk Predictor", layout, use_default_focus=False, finalize=True)
for key in window.key_dict: # Remove dash box of all Buttons
element = window[key]
if isinstance(element, sg.Button):
element.block_focus()
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event in items:
window[event].metadata = True
elif event == "Predict Risk" and window["Mines"].metadata:
print("Predict Risk for Mines")
window.close()

A loop for refreshing page that stop when a button/xpath is clickable

trying to create a loop that refreshes the page continuously until button or xpath becomes available then it will break (dont bully my poor coding i'm new)
if Date == '1':
bool (buttonActive) == False;
list <WebElement> element = driver.find_element_by_xpath('//*[#id="booking-slots-slider"]/div[1]/button')
while (buttonActive):
if (element.size() > 0):
buttonActive = True;
element.get(0).click();
else:
driver.refresh()
List<WebElement> add = driver.find_element_by_xpath('//*[#id="booking-slots-slider"]/div[1]/button')

what to do for non present DIV tag. Using Selenium & Python

I'm trying to extract information with help of selenium and python from this container "PROJECT INFORMATION" //www.rera.mp.gov.in/view_project_details.php?id=aDRYYk82L2hhV0R0WHFDSnJRK3FYZz09
but while do this I was getting this error
Unable to locate element:
{"method":"xpath","selector":"/html/body/div/article/div2/div/div2/div2/div2"}
after studying about it I found that this highlighted div is missing and there are many places in this container where div is missing. How am I supposed to do that? I want information only from the right side of the table
MY CODE:
for c in [c for c in range(1, 13) if (c == True)]:
row = driver.find_element_by_xpath("/html/body/div/article/div[2]/div/div[2]/div["+ str(c) +"]/div[2]").text
print(row, end=" ")
print(" ")
else:
print('NoN')
error:
no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/article/div[2]/div/div[2]/div[2]/div[2]"}
(Session info: chrome=83.0.4103.106)
The fields highlighted are two different cases. While for "Registration Number" the required div does not exist, for "Proposed End Date" it exists but contains only white space.
Give this a try instead of the for c... loop. It should handle both cases.
#find parent element
proj_info=driver.find_element_by_xpath("//div[#class='col-md-12 box']")
#find all rows in parent element
proj_info_rows = proj_info.find_elements_by_class_name('row')
for row in proj_info_rows:
try:
if row.find_element_by_class_name('col-md-8').text.strip() == "":
print(f"{row.find_element_by_class_name('col-md-4').text} contains only whitespace {row.find_element_by_class_name('col-md-8').text}")
print('NaN')
else:
print(row.find_element_by_class_name('col-md-8').text)
except SE.NoSuchElementException:
print('NaN')
You need this import:
from selenium.common import exceptions as SE