PySimpleGui button stuck on Mac - python-3.7
I have a script that runs fine on dell, but seems to work only 70% on mac.
It basically let's the user select different parameters (dates, files, from lists etc), on a while loop until the user presses one of the create buttons that closes the loop.
I removed some parameters for security, but this is the base of the code. The while loop doesn't seem to work, the 3 create buttons don't work, the datepicker doesn't work.
These is my first question, please be kind :)
sg.theme("LightBlue3")
func = ['get_positions_by_account', 'get_positions_by_platform', 'get_positions_by_platform_and_account']
select_all = sg.Listbox(POSITIONS_COLS, select_mode='multiple', key="-IN7-", size=(30,12))
layout = [
[sg.Text("Select account and press go or press PASS to move to select platform:")],
[sg.Combo(ALL_ACCOUNT, key="-IN1-",change_submits=True), sg.Button("GO"), sg.Button("PASS")],
[sg.Text("Select platform:"), sg.Combo([], key="-IN2-",change_submits=True)],
[sg.Text("select run date or date of local file:"), sg.Input(size=(20, 1), key="-IN5-", change_submits=True),
sg.CalendarButton('select', target="-IN5-", key="-IN5-", format='%Y%m%d', default_date_m_d_y=(11, None, 2021))],
[sg.Text("select minimal purchase date:"), sg.Input(size=(20, 1), key="-IN6-", change_submits=True),
sg.CalendarButton('select', target="-IN6-", key="-IN6-", format='%Y-%m-%d', default_date_m_d_y=(11, None, 2021))],
[sg.Text("If local file select file: "), sg.InputText(key="-IN3-", change_submits=True), sg.FileBrowse(key="-IN13-")],
[sg.Text("Select function to run:"), sg.Combo(func, key="-IN4-",change_submits=True)],
[sg.Text('Select position columns:'), sg.Button("Select All"), sg.Button("Top 23"), sg.Button("Clear All")],
[select_all],
[sg.Button("Create position file"), sg.Button("Create transfer file"), sg.Button("Create Talya file"),sg.Button("Exit")]]
window = sg.Window('PIZZA SLICER - Maya Moshe 2021', layout, size=(600, 500))
if __name__ == '__main__':
account, platform, func1, date, pos_file, position, purchase_d = "", "", "", "", "", "", ""
while True:
event, values = window.read()
account = values["-IN1-"]
platform = values["-IN2-"]
pos_file = values["-IN3-"]
func1 = values["-IN4-"]
date = values["-IN5-"]
purchase_d = values["-IN6-"]
pos_cols = values["-IN7-"]
if event == sg.WIN_CLOSED or event == "Exit":
print('Exiting program')
exit()
elif event == "GO":
window["-IN2-"].update(value='', values=ACCOUNTS_PLATFORMS[account])
platform = values["-IN2-"]
elif event == "PASS":
window["-IN2-"].update(value='', values=ALL_PLATFORMS)
platform = values["-IN2-"]
elif event == 'Select All':
cols = POSITIONS_COLS
window.Element('-IN7-').SetValue(cols)
elif event == 'Top 23':
cols = top20
window.Element('-IN7-').SetValue(cols)
elif event == "Clear All":
window.Element('-IN7-').set_value([])
elif event == 'Create position file':
window.close()
now = datetime.datetime.now().replace(microsecond=0)
if pos_file:
position = pd.read_csv(pos_file, dayfirst=True)
eval(func1 + "(date=date, account=account, platform=platform, position=position, purchase_d=purchase_d, cols=pos_cols)")
diff = datetime.datetime.now().replace(microsecond=0) - now
print(f'pos filter, run time {diff}')
exit()
elif event == "Create transfer file":
window.close()
now = datetime.datetime.now().replace(microsecond=0)
if pos_file:
position = pd.read_csv(pos_file, dayfirst=True)
get_positions_by_account(date=date, account=account, platform=platform, position=position, purchase_d=purchase_d, cols=pos_cols, transfer_flag=True)
diff = datetime.datetime.now().replace(microsecond=0) - now
print(f'Create transfer file, run time {diff}')
exit()
break
elif event == "Create Talya file":
window.close()
now = datetime.datetime.now().replace(microsecond=0)
if pos_file:
position = pd.read_csv(pos_file, dayfirst=True)
get_positions_by_account(date=date, account=account, platform=platform, position=position, purchase_d=purchase_d, cols=pos_cols, talya_flag=True)
diff = datetime.datetime.now().replace(microsecond=0) - now
print(f'Create Talya file, run time {diff}')
exit()
Example Code here to show both of buttons Exit and Select All work. Nothing wrong found, maybe wrong code missed in your demo code.
import PySimpleGUI as sg
lst1 = list("ABCDEFGHIJ")
layout = [
[sg.Button('Select All')],
[sg.Listbox(lst1, size=(5, 10), select_mode='multiple', key='-IN7-')],
]
window = sg.Window("test", layout, finalize=True)
while True:
event, values = window.read()
if event in (sg.WINDOW_CLOSED, 'Exit'):
print('Exiting program')
break
# Get value of elements should be here to prevent value of `values` is None when sg.WINDOW_CLOSED
pos_cols = values["-IN7-"]
if event == 'Select All':
window['-IN7-'].set_value(lst1)
window.close()
Related
Can an automated apps script email notification link back to specific sheet?
much to my surprise I've successfully made an apps scripts that sends me email notifications when a specific cell is changed to 'Submitted,' but I have no idea how to make this identify the sheet it came from - have linked a copy of the sheet below, there are going to be around 20 of these, each with 6 submission sheets, and I need to do a thing as soon as the sheet has been marked submitted, i.e. same day. I'd rather not hard code in separate messages for each sheet, can I do something around getting the URL and sheet with the get active sheet coding and insert it into the email message? I'm also aware currently I've hard coded in the sheet names and therefore need 6 different triggers, I'm working on that - tried loads of different coding pages and this is the only one that worked! https://docs.google.com/spreadsheets/d/1b0LOr9vhmFu4WtYy_RbS-1cvXncNOI_x3YT0f30fZgY/edit#gid=1979912158 Cheers, Meg function emailSubmit() { MailApp.sendEmail("Testemail", "Test", "Test message"); } function onEdit(e) { const specificSheet = "Sub1" const specificCell = "C11" let sheetCheck = (e.range.getSheet().getName() == specificSheet) let cellCheck = (e.range.getA1Notation() == specificCell) if (!(sheetCheck && cellCheck) || e.value !== "Submitted") { return; } else { emailSubmit() } } function onEdit2(e) { const specificSheet = "Sub2" const specificCell = "C11" let sheetCheck = (e.range.getSheet().getName() == specificSheet) let cellCheck = (e.range.getA1Notation() == specificCell) if (!(sheetCheck && cellCheck)) { return } else { emailSubmit() } }
To obtain the spreadsheet object bound to the fired onEdit trigger, use the event object source Sample: function emailSubmit(spreadsheet, sheet) { console.log("spreadsheet: " + spreadsheet); console.log("sheet: " + sheet); MailApp.sendEmail("Testemail", "Test", "Spreadsheet " + spreadsheet + " and tab " + sheet + "have been submitted"); } function onEdit(e) { const allowedSheets = ["Sub1","Sub2"]; const specificCell = "C11"; const spreadsheetName = e.source.getName(); const sheetName = e.range.getSheet().getName(); let sheetCheck = (allowedSheets.indexOf(sheetName) != -1); let cellCheck = (e.range.getA1Notation() == specificCell); if (!(sheetCheck && cellCheck) || e.value !== "Submitted") { return; } else { emailSubmit(spreadsheetName, sheetName); } } References: Event Objects getName() indexOf()
VSCode Open a File In a Specific Line Number Using JS
I added a new button to my VSCode, such that when I click it - it compiles the current folder, and shows dialog boxes using vscode.window.showInformationMessage. Each box shows a compilation error, and has a button in it. Once the user clicks the button - it opens the problematic file in a tab using vscode.workspace.openTextDocument. I want to make the button to also navigate me to the problematic line in the problematic file. My question is: Given a number, is it possible to navigate to a specific line number inside a file? Sample code of what I achieved so far: // Bullshit to give some context const pattern = /(In \w+.jack)/g; var i = s.search(pattern); var substring = s.substring(i + 1) var j = substring.search(pattern); var s = "bsadsdbla In main.jack (line 55) sqdwqe blasdsd wq qqweq" let GoToFile = 'Go to File'; var k = s.search(/(\w+.jack)/); var l = s.search(/(.jack)/) var fileName = s.substring(k, l); // ---------> This is the important part <---------------- vscode.window.showInformationMessage(s.substring(i, j), GoToFile).then(selection => { if (selection === GoToFile) { vscode.workspace.openTextDocument(currentDirectory + '\\' + fileName + '.jack') .then(document => vscode.window.showTextDocument(document)); } });
I am assuming you have some code/regex in place that gives you the line number. Whenever someone clicks your GoToFile method invoke the following code : activeEditor.selections = [new vscode.Selection(lineToGo, lineToGo)]; var range = new vscode.Range(lineToGo, lineToGo); activeEditor.revealRange(range);
Some background: As #rioV8 mentioned, revealRange was the way to go, but the problem was that I couldn't understand how to use it using the VSCode API, so here #Shahriar Hossain came into the picture. #Shahriar Hossain's code works, however, there was an important declaration missing, and I also had to figure out how to run the code when the user clicks the button. This is the full solution: vscode.window.showInformationMessage(s.substring(i), GoToFile).then(selection => { if (selection === GoToFile) { vscode.workspace.openTextDocument(currentDirectory + '\\' + fileName + '.jack') .then(document => vscode.window.showTextDocument(document)) // Whatever code inside this "then" block // will be executed on button click .then(x => { let m = s.substring(i, j).search(/\(line \d+\)/); let subStr = s.substring(m + 6); let n = subStr.search(/\)/); subStr = subStr.substring(0, n); let lineToGo = parseInt(subStr.match(/\d+/)); // The missing declaration of the activeEditor let activeEditor = vscode.window.activeTextEditor; let range = activeEditor.document.lineAt(lineToGo - 1).range; activeEditor.selection = new vscode.Selection(range.start, range.end); activeEditor.revealRange(range); }) } });
PyQt 4 / Qt 4 move QGraphicsItem with mouse using custom event handler
I am developing an application using pyqt 4 so hopefully I am only making a rookie mistake. I found I cannot move a QGraphicsItems and QGraphicsItemGroups in a scene once I use custom event handlers for mousePressEvent() and mouseMoveEvent(). My application permits me to draw arbitrary shapes however I press CTRL key modifier to set my event handlers so that I can select objects (and add them to QGraphicsItemGroup) to move all selected objects. from PyQt4 import QtCore, QtGui from PyQt4.QtCore import * from PyQt4.QtGui import * class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.view = View(self) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.view) self.setMouseTracking(True) def __init__(self, parent): QtGui.QGraphicsView.__init__(self, parent) self.activeScene=QtGui.QGraphicsScene(self) self.setScene(self.activeScene) self.setInteractive(True) self.setSceneRect(QtCore.QRectF(self.viewport().rect())) self.startpos = None self.endpos = None self.multiSegmentLine = QtGui.QGraphicsItemGroup(scene=self.activeScene) self.multiSegmentLine.setFlags(QtGui.QGraphicsItemGroup.ItemIsSelectable) self.linePen=QPen(Qt.green, 3, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) self.linesegment=QtGui.QGraphicsLineItem # Create a group of selected items to move as a group self.createMoveGroup = QtGui.QGraphicsItemGroup(scene=self.activeScene) self.createMoveGroup.setFlags(QtGui.QGraphicsItemGroup.ItemIsMovable) # TESTING self.boxxy = self.activeScene.addRect(10,10,100,100,self.linePen) self.boxxy.setFlags(QtGui.QGraphicsItem.ItemIsMovable) # Booleans for state machine self.stateNewLine=True # Flag to determine line state True = new line, False = continuation of multisegment line self.stateSelectItems=False # Flag to help determine True = item selection mode enabled, False = line drawing mode enabled # Create event handler def mousePressEvent(self, event): if event.button()==QtCore.Qt.LeftButton: # If CTRL key is not pressed then self.stateSelectItems is FALSE and # mouse handling is normal if self.stateSelectItems == False: # New line has been started so no end point has been determined if self.stateNewLine == True: # Record starting position if creating a new line. This is used as # origin for line drawn from start position to mouse tip. self.startpos = QtCore.QPointF(self.mapToScene(event.pos())) # The line is not new but rather is a multiple segment line. elif self.stateNewLine == False: # Update the length of the run UserLineList.updateRunLength(self.linesegment.line()) self.startpos = self.endpos # Start new line at endpoint of previous segment self.segmentCount = self.segmentCount+1 # increment segment count #self.multiSegmentLine.setFlag(QtGui.QGraphicsItem.ItemIsMovable) # Add line from starting position to location of mouse click #self.linesegment=self.scene().addLine(QtCore.QLineF(self.startpos,self.endpos)) self.linesegment = self.activeScene.addLine(QtCore.QLineF(self.startpos,self.endpos)) self.linesegment.setPen(self.linePen) # Add newly created line to item group self.multiSegmentLine.addToGroup(self.linesegment) self.activeScene.addItem(self.multiSegmentLine) self.activeScene.removeItem(self.linesegment) # If CTRL key is pressed thenself.stateSelectItems == True and mouse # handling has to change to support moving one or more screen items elif self.stateSelectItems==True: print("ENTERED MOVEMENT MODE!") currentItem=self.activeScene.itemAt(self.mapToScene(event.pos())) if currentItem != None: self.createMoveGroup.addToGroup(currentItem) self.stateSelectItems = True # set stateSelectItems flag to control mouse event handling def mouseDoubleClickEvent(self,event): #def mouseReleaseEvent(self, event): if event.button() == QtCore.Qt.LeftButton: self.startpos=None self.stateNewLine=True # multisegment line has ended # Create a record of the multisegment line UserLineList.addMultiSegmentLine(self.multiSegmentLine) def mouseMoveEvent(self,event): # If CTRL key is not pressed then self.stateSelectItems is FALSE and # mouse handling is normal if self.stateSelectItems == False: # If this is a new line use start position at click if self.stateNewLine == True: self.endpos = QtCore.QPointF(self.mapToScene(event.pos())) self.linesegment = self.activeScene.addLine(QtCore.QLineF(self.startpos,self.endpos)) self.linesegment.setPen(self.linePen) self.stateNewLine = False # If this line builds upon an existing segment elif self.stateNewLine == False: self.endpos = QtCore.QPointF(self.mapToScene(event.pos())) self.scene().removeItem(self.linesegment) self.linesegment = self.activeScene.addLine(QtCore.QLineF(self.startpos,self.endpos)) self.linesegment.setPen(self.linePen) # If CTRL key is pressed thenself.stateSelectItems == True and mouse # handling has to change to support moving one or more screen items elif self.stateSelectItems == True: self.createMoveGroup.mouseMoveEvent(self, event) def keyPressEvent(self,event): keyModifier = QtGui.QApplication.keyboardModifiers() #Listen for keyboard modifier keys if keyModifier == QtCore.Qt.ControlModifier: print("keyEvent Control Key is pressed") self.stateSelectItems=True def keyReleaseEvent(self,event): keyModifier = QtGui.QApplication.keyboardModifiers() #Listen for keyboard modifier keys if keyModifier == QtCore.Qt.ControlModifier: self.stateSelectItems=False self.createMoveGroup.ungrabMouse() # Selected items lose mouse grab self.activeScene.destroyItemGroup(self.createMoveGroup) # Remove all selected items from move group if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.resize(640, 480) window.show() sys.exit(app.exec_())
Like in the answer to this question, you might want to do a call to the base-class in order to keep the existing event handling of the respective event. E.g. in the mouse press event handler you would add a line like: def mousePressEvent(self, event): ... super(Window, self).mousePressEvent(event) ... Do this in a similar way for all your custom event handlers.
Row coloring in Google Apps Script onEdit and onOpen?
I have create a Google form that submits data to a Google spreadsheet. I am trying to color code rows based on a value in a specific column - no problem. However, I am using the onEdit function and when a user submits the form, the rows do not change color. It is only when I edit the specific cell that the the row changes color, hence the onEdit function. Do, Google does not appear to see a form submission as an "edit" in the spreadsheet even though it is, technically, an edit. I have tried to copy and paste the function and rename it to onOpen, but that does not work either. What am I missing here? I have posted the code below and I really appreciate any help that you can afford. Also, I am a newb to scripting, so please be easy on me ;) // Color code rows based on the status of the ticket function onEdit(e) { if (e) { var ss = e.source.getActiveSheet(); var r = e.source.getActiveRange(); // If you want to be specific // do not work in first row // do not work in other sheets except "Sheet1" if (r.getRow() != 1 && ss.getName() == "Sheet1") { // E.g. status column is 6th (F) status = ss.getRange(r.getRow(), 6).getValue(); // Specify the range with which You want to highlight // with some reading of API you can easily modify the range selection properties // (e.g. to automatically select all columns) rowRange = ss.getRange(r.getRow(),1,1,6); // This changes row color if (status == 'New') { rowRange.setBackgroundColor("#f26c4f"); } else if (status == 'In Progress') { rowRange.setBackgroundColor("#fff568"); } else if (status == 'Ordered') { rowRange.setBackgroundColor("#68baff"); } else if (status == 'Completed') { rowRange.setBackgroundColor("#a2e7a5"); // DEFAULT } else if (status == '') { rowRange.setBackgroundColor("#FFFFFF"); } } } }
"Google does not appear to see a form submission as an "edit" in the spreadsheet even though it is, technically, an edit" That's why there is an On form submit feature, see documentation here, available from the script editor ressources > current script triggers
forced_root_block option in TinyMCE
I am trying to implement a custom WYSIWYG editor using a contenteditable <div>. One of the major issues I am facing is the inconsistent way browsers handle ENTER keystroke (linebreaks). Chrome inserts <div>, Firefox inserts <br> and IE inserts <p>. I was taking a look at TinyMCE and it has a configuration option called forced_root_block. Setting forced_root_block to div actually works across all major browser. Does someone know how forced_root_block option in TinyMCE is able to achieve it across browsers ?
In the tinymce source (/tiny_mce/classs/dom/DomParser.js) you will find the following: rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block; whiteSpaceElements = schema.getWhiteSpaceElements(); startWhiteSpaceRegExp = /^[ \t\r\n]+/; endWhiteSpaceRegExp = /[ \t\r\n]+$/; allWhiteSpaceRegExp = /[ \t\r\n]+/g; function addRootBlocks() { var node = rootNode.firstChild, next, rootBlockNode; while (node) { next = node.next; if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) { if (!rootBlockNode) { // Create a new root block element rootBlockNode = createNode(rootBlockName, 1); rootNode.insert(rootBlockNode, node); rootBlockNode.append(node); } else rootBlockNode.append(node); } else { rootBlockNode = null; } node = next; }; }; This obviously takes care of creating root block elements. I am 99% sure that tinymce handles the 'ENTER' keystroke itself and stops the propagation/ default browser command.