How to use a button in bottle? - python

I am making a simple currency exchanger with Bottle.
I want to make a submit button so that when I click it, some text will be triggered on the page I am on.
So far I only know how to make a new template so that the button takes me to a new page, but I don't know how to add it to the page I am on.
import bottle
def exchanger():
amount = float(bottle.request.forms["amount"])
currency1 = bottle.request.forms["currency1"]
valuta2 = bottle.request.forms["currency2"]
return bottle.template("result.html",
calculate=calculate,
amount=amount,
currency1=currency1,
currency2=currency2)

Related

when i enter a video name to the input variable the vidplayer() function doesn't look for it but plays a random video on youtube

I'm trying to build a gui interface where i can enter the title of a video and once i click on the button, the selenium function (vidplayer) will look for the video on youtube and play the first one of the result page.
Everything works fine except when i click on the button the selenium function plays the first video on my youtube HOMEPAGE instead of looking for the one i chose earlier
from selenium import webdriver
from tkinter import *
root=Tk()
root.title('Youtube Video Player')
text=Label(root,text="In order to save time and avoid procrastination.\nEnter the name of the video
you have in mind,and by the power of the gods it will play")
text.pack()
input=Entry()
input.pack()
a=str(input.get())
#playing the video with the 'a' variable title on youtube
def vidplayer():
browser=webdriver.Chrome('C:\\Users\\lenovo\\Downloads\\chromedriver')
browser.get('https://www.youtube.com/results?search_query='+a)
video=browser.find_element_by_id('video-title')
video.click()
button=Button(text="Play Video", command=vidplayer)
button.pack()
root.mainloop()
The problem is that you're calling a.get() about a millisecond after creating the entry widget, well before the user has a chance to enter anything.
The fix is simple: get the value when you actually need it, and not before:
def vidplayer():
query = input.get()
url = 'https://www.youtube.com/results?search_query='+query
browser=webdriver.Chrome('C:\\Users\\lenovo\\Downloads\\chromedriver')
browser.get(url)
...

Dash modal with multiple buttons that open it

Following this part of the docs: https://dash-bootstrap-components.opensource.faculty.ai/l/components/modal I've created a modal in my Dash app. The trigger for the modal will be dynamically rendered thumbnails. When any of them is clicked, the modal should open and display the image from the thumbnail as it's body.
Is is possible, inside Dash, to have multiple buttons (I don't know how many will there be, depending on how many thumbnails in the database) that will all open the same modal dialog and pass some of their data to the modal (such as img src in my case)?
The input in the example above is simple:
[
Input("open", "n_clicks"), Input("close", "n_clicks")
],
but in reality I don't know how many will there be and can't hardcode an ID.
Any suggestions?
Yes, you can have multiple buttons open a modal. Just as you showed, the callback would have an Input for each one. No, you cannot create them dynamically. Dash does not play well with any ID that is not in the layout at the start of running the app.
Create a set of buttons dynamically using the below list comprehension:
[dcc.Button(x, id={'type': 'thumbnail_button', 'index': x}) for x in thumbnail_list]
Use the pattern-matching callback to open modal when any of these buttons are clicked:
#app.callback(
Output('your-modal', 'is_open'),
[Input({'type': 'thumbnail_button', 'index': ALL}, 'n_clicks')]
)
def handle_button_click(n_clicks):
invoker = [p['prop id'] for p in dash.callback_context.triggered][0]
invoker_type = json.loads(invoker.split('.')[0])['type']
invoker_index = json.loads(invoker.split('.')[0])['index']
if invoker_type == "thumbnail_button":
return not is_open
else:
return is_open
Lastly the imports:
from dash.dependencies import Input, Output, ALL

When a QPushButton is clicked, it fires twice

I used PyQt5 for a project and have the following snippet (button is a QPushButton)
def on_receive(self, query):
print("receiving", query)
datapackages = json.loads(query)
for button, datapackage in zip(self.buttonArray, datapackages):
self.wire_up_button(datapackage, button)
def wire_up_button(self, datapackage, button):
title, songid = datapackage["title"], datapackage["songid"]
button.setText(title + " (" + str(datapackage["votes"]) + ")")
button.clicked.connect(lambda: self.upvote(songid))
def upvote(self, sid):
text = '{"action":"upvote", "value":"' + sid + '"}\n'
print(text)
self.send(text)
def send(self, text):
print("Sending")
The on_receive function is connected to a soccet client and will be called wheneever a data package is received. The layout is a bit complicated because my UI has so many buttons it's handier to iterate over them than to hard-code every single one.
Whenever I click the button, the wire-up function wires the button to the upvote function, which creates a json protocl and sends it to the socket server. However, the wireup-function is called twice per click. (I am certain of this because of the debug print commands). There is no other call in the send function in my program.
I speculate that this might be due to how clicked.connect works (maybe it fires upon click and release).
I used the QtDesigner to create the UI and loaded the .uic in my main.py
Every time you receive anything from socket you do
for button, datapackage in zip(self.buttonArray, datapackages):
self.wire_up_button(datapackage, button)
and in self.wire_up_button you connect to button clicked event. Note, that self.buttonArray is always the same list of buttons, so every time on_receive is called you add 1 new subscription to each button click. But previous subscription to button click still exists, so on button click upvote will be called multiple times with different sid. You need to disconnect from button click event before adding new one:
def wire_up_button(self, datapackage, button):
try:
button.clicked.disconnect()
except:
pass
title, songid = datapackage["title"], datapackage["songid"]
button.setText(title + " (" + str(datapackage["votes"]) + ")")
button.clicked.connect(lambda: self.upvote(songid))
try ... except block is required, because button.clicked.disconnect() raises exception if no functions were connected to click event.

PyWinAuto trouble clicking the Next Button

This code gets the first window from InstallShield.
from pywinauto import application
from pywinauto import findwindows
app = application.Application()
app.start("MyInstallShieldApp.exe")
time.sleep(15)
hwnd = findwindows.find_windows(title=u"InstallShield Wizard", class_name="MsiDialogCloseClass")
print ("|", str(hwnd), "|")
dlg = app.Window_(handle=hwnd).Wait("enabled", timeout=25, retry_interval=0.5)
Now I want to click the Next button. Swapy says that the Next button has the text '&Next >' and the Button number is 1. But none of these click statements have any effect.
dlg.Click("Next")
dlg.Click(coords=(977, 711))
dlg.Click(button="left")
You misapply Click method. It has the next signatire - Click(button=u'left', pressed=u'', coords=(0, 0), double=False, absolute=False)
To click a button, click should be performed on the button object. So you shoud navigate to the button at first.
In your case the code may look something like:
dlg['&Next >'].Click()
Again, please do not guess, read the docs and see the examples

Add right-click functionality to listwidget in PyQt4

Im trying to add right-click functionality to items in a list widget in PyQt4 using Python. Id like a pop up context menu to show that has buttons and when clicked should perform some function.
How do I get a context menu to pop up when right clicking on each of the items?
I have come up with a pretty simple way of doing this and works perfectly. In the ControlMainWindow class add the following to initialise the Context menu policy as CustomeContextMenu where listWidget_extractedmeters will be the name of your QListWidget:
self.listWidget_extractedmeters.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listWidget_extractedmeters.connect(self.listWidget_extractedmeters,QtCore.SIGNAL("customContextMenuRequested(QPoint)" ), self.listItemRightClicked)
Then in the ControlMainwindow class the following functions allow you to add context menu items and to call a funtion that performs some functionality:
def listItemRightClicked(self, QPos):
self.listMenu= QtGui.QMenu()
menu_item = self.listMenu.addAction("Remove Item")
self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.menuItemClicked)
parentPosition = self.listWidget_extractedmeters.mapToGlobal(QtCore.QPoint(0, 0))
self.listMenu.move(parentPosition + QPos)
self.listMenu.show()
def menuItemClicked(self):
currentItemName=str(self.listWidget_extractedmeters.currentItem().text() )
print(currentItemName)

Categories