Streamlit button works only once - streamlit

I want to create a simple streamlit application, that when you press the button, it increments x and shows the new value of x.
However, it works only for the 1st time "x only shows the value 2 and doesn't increment"
import streamlit as st
x = 1
if st.button("Increment x"):
x=x+1
st.text(x)

Streamlit re-runs the webpage script every time you make a change/interaction. So each time you click the button it resets x=1, then adds 1 to x.
Your button is working correctly, the issue is in the way streamlit handles events. You could try using st.cache to work around this, but I've never tried to replicate what you're aiming for.

https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92
Hey, this package worked wonders for me.
Download the code into the same folder you're working on and boom:
import SessionState
ss = SessionState.get(x=1)
if st.button("Increment x"):
ss.x = ss.x + 1
st.text(ss.x)

Streamlit's session state makes it possible to increment a value with the click of a button.
import streamlit as st
btn = st.button("Press Me")
if btn:
if 'x' in st.session_state.keys():
st.session_state['x']=st.session_state['x']+1
else:
st.session_state['x']=1
if 'x' in st.session_state.keys():
st.write(st.session_state['x'])
X will increment by 1 for each button click.

Related

Selenium stopping mid-loop without any error or exception

I was working on a project to scrap data for multiple cities from a website. There are about 1000 cities to scrap and during the for-loop, the webdriver window simply stops going to the requested site. However, the program is still running and no error or exception is thrown, the webdriver window just simply stays at the same webpage.
There is a common feature regarding the webpage that it stopped at, which is the windows are always the ones requesting the button clicks. The button click parts of the code should be correct as it is working as desired for hundreds of cities before the suspension.
However, every different run the program is stopping at different cities and I find no correlation between the cities, which leaves me very confused and unable to identify the root of the problem.
data_lookup = 'https://www.numbeo.com/{}/in/{}'
tabs = ['cost-of-living', 'property-investment', 'quality-of-life']
cities_stat = []
browser = webdriver.Chrome(executable_path = driver_path, chrome_options=ChromeOptions)
for x in range(len(cities_split)):
city_stat = []
for tab in tabs:
browser.get(data_lookup.format(tab, str(cities_split[x][0])+'-'+str(cities_split[x][1])))
try:
city_stat.append(read_data(tab))
except NoSuchElementException:
try:
city_button = browser.find_element(By.LINK_TEXT, cities[x])
city_button.click()
city_stat.append(read_data(tab))
except NoSuchElementException:
try:
if len(cities_split[x]) == 2:
browser.get(data_lookup.format(tab, str(cities_split[x][0])))
try:
city_stat.append(read_data(tab))
except NoSuchElementException:
city_button = browser.find_element(By.LINK_TEXT, cities[x])
city_button.click()
city_stat.append(read_data(tab))
elif len(cities_split[x]) == 3:
city_stat.append(initialize_data(tab))
except:
city_stat.append(initialize_data(tab))
cities_stat.append(city_stat)
I have tried using WebDriverWait to no appeal. All it does is simply make the NoSuchElementException become a TimeoutException.

tkinter how do i save changes made to the buttons

thx a lot for replying my questions for making my previous code simpler.. this is the result... now for the next phase is save changes made to the buttons.. im still learning though looking for sources anything can help :)
from tkinter import*
import tkinter as tk
import tkinter.simpledialog
def onChange(i):
btn_list[i].config(text='Updating...',bg='red')
btn_list[i].grid(in_=root,row=rw[i],column=2)
ans=tk.simpledialog.askfloat('Updating....', 'What is the current price?')
if ans:
btn_list[i].config(text='RM{:,.2f}'.format(ans))
btn_list[i].config(bg='yellow')
root=Tk()
Title=['Item','Unit','Price']
Item=['Kopi O','Teh O','Teh Tarik']
Unit= '1 cup'
Price=[1,0.9,1.2]
cl=[0,1,2]
rw=[1,2,3]
btn_list=[]
for i in range(3):
btnT1=tk.Button(root,text=Title[i],width=10,bg='light green')
btnT1.grid(in_=root,row=0,column=cl[i])
for x in range(3):
btnT2=tk.Button(root,text=Item[x],width=10)
btnT2.grid(in_=root,row=rw[x],column=0)
for y in range(3):
btnT3=tk.Button(root,text=Unit,width=10)
btnT3.grid(in_=root,row=rw[y],column=1)
for z in range(3):
btnT4=tk.Button(root,text=('RM {:,.2f}'.format(Price[z])),bg='yellow',width=10,\
command=lambda i=z:onChange(i))
btnT4.grid(in_=root,row=rw[z],column=2)
btn_list.append(btnT4)
root.mainloop()
If you want changes to be saved when your program exits and restarts, you'll have to do all of the work yourself. You'll need to write a function that gathers all the data you want to save, another function to write that data to a file or database, a third to be able to read the data from the file or database, and a forth to update the UI with the saved values.

Run command when X button is clicked

Currently I working with maya and I want to execute a command when I close a window.
So far I haven't found any solution to run a command when the windows X button is clicked except to create a custom button and use deleteUI..
Is there a flag or something to so it easier?
You could use a scriptJob. It will run a process in the background based on your conditions.
from pymel.core import *
win = window()
win.show()
def uiDel(ui):
print ui, "deleted"
scriptJob(uid=[win.name(), "uiDel(win.name())"])
Now when the ui is closed, or the X button is pressed, it will print "window1 deleted".

In Tkinter how do def work?

I made a Tkinter book on a grid, the navergation buttons scroll down the left row and the photos are displayed on the right column spaning many rows so buttons display as they should. When making this Tkinter book.
I made a button on a grid
left1 = Button(win, text=" Captian Scarlet ")# win, is root master
left1.configure(command=but1)# but1 is my first def
left1.grid(row=1, column=0)# all the buttons are on the left list
This displays and works like a button without a def
Then I made a def
def but1():
img = Image.open("captain_scarlett.gif")# loads the gif file
intro = ImageTk.PhotoImage(img)# loads image drivers I belevie
right1 = Label(win, image=intro)# I think Lable is used the same as html <span>
right1.grid(row=0, column=1, rowspan=13)# image formatting to display correctly with buttons
Because I had a lack of education at the time, I could only get the image to displaplay outside a def. So in frustration I posted
"this code works purfect when not put into a def".
When I settled down I needed knowledge that I couldn't find online so I asked the question:
So How do I get this code to work inside a def ?
What makes you think it doesn't work? There's nothing special about Tkinter in this regard; anything that works outside a def definitely works inside a def. The only caveats are the same for all python code. For example, any variables you create inside the def are local unless declared otherwise, and objects (but not widgets) may get garbage collected after the def executes.
Probably what is happening is that you're creating the image and storing a reference to it in a local variable. When the def stops executing the image object is garbage collected. You'll need to keep a reference to the image that can persist. One simple solution might be to do right1.image=intro.
This code works purfecty. Now my production can go full steam ahead
Here is the finished code
def but1():
img = Image.open("captain_scarlett.gif")
intro = ImageTk.PhotoImage(img)
right = Label(win, image=intro)
right.grid(row=0, column=1, rowspan=14)
right.image=intro

Displaying 2nd Window Issue

I am dealing with 2 windows . One is created by Qt Designer and i import it
on test.py program . what i did i make a Widget on the test program and
than add a button to it and on click event I try to popup the other
window(gui1.py) created by Qt Designer but it never pop ups and when i use
break and do line by line debugging it shows me this message after running
this command "myapp2 = MyForm()" on line number 35 test.py .
QCoreApplication::exec: The event loop is already running
and once i pressed enter on the terminal it pop up the other window .
I am confuse where i am wrong .
Thanks
test.py
gui1.py
The reason the other window doesn't appear, is because you are not keeping a reference to it, and so it gets garbage-collected immediately after it is shown.
To fix the problem, you could either store the window instance it as an attribute, or give it a parent:
def local_manag(self):
print "pressed"
# store it as an attribute
self.myapp2 = MyForm()
self.myapp2.show()
# or give it a parent
# myapp2 = MyForm(self)
# myapp2.show()

Resources