Issue with refreshing values in a Tkinter window - python

Here is the code:
import steammarket as sm
import time
from tkinter import *
from PIL import ImageTk, Image
#Search function which gets the request from the market
name = ('Operation Broken Fang Case')
item = sm.get_csgo_item(name, currency='GBP')
#GUI
window = Tk()
window.title("OSMA")
window.geometry("300x110")
Lbl = Label(window, text=name, font= ('Helvetica 9 underline'))
Lbl.grid(column=0, row=0)
#Image for case
image1 = Image.open("FangCase.png")
case1 = ImageTk.PhotoImage(image1)
label1 = Label(image=case1)
label1.image = case1
label1.place(x=20, y=20)
Lbl = Label(window, text='Average cost: '+item["median_price"])
Lbl.grid(column=1, row=3)
Lbl = Label(window, text='Lowest cost: '+item["lowest_price"])
Lbl.grid(column=1, row=4)
Lbl = Label(window, text='Listings: '+item["volume"])
Lbl.grid(column=1, row=5)
#Waits 10 mins, searches again and refreshes value
def refresh():
name = ('Operation Broken Fang Case')
item = sm.get_csgo_item(name, currency='GBP')
print(item)
window.after(300000, refresh)
refresh()
window.mainloop()
I'm trying to get the last 3 labels to refresh the values and display them. Although the values are refreshed, it doesn't display the new values instead of the old ones.
I've looked at a previous question on how to do refreshing, and used said code from the question as a basis
Any help is appreciated,

Related

How do I get the Value of Tkcalendar/Date Entry

hi I am building a GUI where it should be possible to insert your name and your brthday that get´s stored in a sqllite3 database.
I use the Tkcalendar module to let the person choose it´s birthday.
My problem is I don´t know how to read out the Date.
I hope somebody can help me!
import sqlite3
verbindung = sqlite3.connect("Datenbanken/geb3.db")
zeiger = verbindung.cursor()
zeiger.execute("""CREATE TABLE IF NOT EXISTS people3(vorname VARCHAR(20), nachname VARCHAR(30), geburtstag DATE );""")
from tkinter import *
from tkcalendar import Calendar, DateEntry
root = Tk()
def speichern():
zeiger.execute("""INSERT INTO people3 VALUES (?,?,?) """, (eingabefeldvorname.get(), eingabefeldnachname.get(), eingabefelddatum.get()))
Label(root, text = "vorname").pack()
eingabefeldvorname=StringVar()
eingabefeld = Entry(root, textvariable = eingabefeldvorname, bg ="red").pack()
Label(root, text = "nachname").pack()
eingabefeldnachname = StringVar()
eingabefeld = Entry(root, textvariable = eingabefeldnachname, bg ="green").pack()
Label(root, text = "Geburtsdatum")
eingabefelddatum= DateEntry(root, width = 20, textvariable = eingabefelddatum, bg ="yellow").pack()
konpf2 = Button(root, text = "speichern", command = speichern).pack()
root.mainloop()
zeiger.execute("SELECT * FROM people3")
inhalt = zeiger.fetchall()
print(inhalt)
def listeleeren():
zeiger.execute("DELETE FROM people3")
listeleeren()
verbindung.commit()
verbindung.close()```
To get the value of DataEntry, the fuction get_date() works.
Reference: https://pypi.org/project/tkcalendar/#dateentry-widget
also you can use a <<DateEntrySelected>> event which is generated each time the user selects a date with the mouse.
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
def dateentry_view():
def print_sel(e):
print(cal.get_date())
top = tk.Toplevel(root)
ttk.Label(top, text='Choose date').pack(padx=10, pady=10)
cal = DateEntry(top, width=12, background='darkblue',
foreground='white', borderwidth=2)
cal.pack(padx=10, pady=10)
cal.bind("<<DateEntrySelected>>", print_sel)
root = tk.Tk()
ttk.Button(root, text='DateEntry', command=dateentry_view).pack(padx=10, pady=10)
root.mainloop()

Tkinter label widget showing variable two times

I am trying to create a corona tracker using a entry widget except everytime i try to search two times the search result shows two times. Here is the picture.
I have tried deleting the variable when the button widget but it didnt work.
import sqlite3
import tkinter
db = sqlite3.connect ('covidjakartadb.db')
window = tkinter.Tk()
window.geometry("500x300")
window.title("Corona tracker")
label = tkinter.Label(window, text="Please enter a area")
label.pack()
entry = tkinter.Entry(window)
entry.pack()
def Search_Completed():
# select_all = "SELECT * FROM locations WHERE '%{0}%'".format(entry)
select_all = "SELECT positive FROM locations WHERE City LIKE '%{0}%'".format( entry.get() )
cursor = sqlite3.Cursor(db)
cursor.execute(select_all)
positive = cursor.fetchall()
print (positive)
tkinter.Label (window, text=positive, font='Ariel 25 bold').pack()
tkinter.Label (window, text="Tips to fight off the coronavirus")
Button = tkinter.Button(window, text="Search data", command=Search_Completed)
Button.pack()
window.mainloop()
Try this :
import sqlite3
import tkinter
db = sqlite3.connect ('covidjakartadb.db')
window = tkinter.Tk()
window.geometry("500x300")
window.title("Corona tracker")
label = tkinter.Label(window, text="Please enter a area")
label.pack()
entry = tkinter.Entry(window)
entry.pack()
def Search_Completed():
result["text"] = ""
# select_all = "SELECT * FROM locations WHERE '%{0}%'".format(entry)
select_all = "SELECT positive FROM locations WHERE City LIKE '%{0}%'".format( entry.get() )
cursor = sqlite3.Cursor(db)
cursor.execute(select_all)
positive = cursor.fetchall()
print (positive)
result["text"] = positive
Button = tkinter.Button(window, text="Search data", command=Search_Completed)
Button.pack()
result= tkinter.Label (window, text=positive, font='Ariel 25 bold')
result.pack()
window.mainloop()

Refresh my tkinter label and lets it overwrite it with different output content

I have a Submit button that prints the output on the tkinter widget label. Everytime I change the input and click the Submit the output is displayed but not at the same place i.e. The previous content of the label is not overwritten.
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("ImageValidation ")
root.geometry("600x600+100+100")
pathlist = [None, None] # holds the two files selected
labels = []
def browse_button(index):
global filename
filename = filedialog.askopenfilename(title = "Choose your file",filetypes = (("jpeg files","*.jpeg"),("all files","*.*")))
pathlist[index] = filename
heading = Label(root, text = "Select 2 images you want to Validate",
font=("arial",15,"bold","underline"), fg="blue").pack()
label1 = Label(root, text = "Enter Image 1", font=("arial",10,"bold"),
fg="black").place(x=10, y = 100)
label2 = Label(root, text = "Enter Image 2", font=("arial",10,"bold"),
fg="black").place(x=10, y = 200)
button = Button(root,text="Choose an Sign1",width = 30,command= lambda:
browse_button(0)).place(x=250, y= 100)
button = Button(root,text="Choose an Sign2",width = 30,command=
lambda: browse_button(1)).place(x=250, y= 200)
def display():
ImageVerification(pathlist[0], pathlist[1])
l1 = Label(root,text=Scriptoutput, width = 200 )
l1.pack(side='bottom', padx=50, pady=50)
#Scriptoutput is the output variable from the main code.
submit_button = Button(text="Submit", width=15,command = display)
submit_button.pack(side='bottom', padx=15, pady=15)
root.mainloop()
A 'refresh' button that would clear the Label of its content and lets you overwrite it.
I am taking your function ImageVerification() as a blackbox and assuming it is working.
The reason this is happening is because you create a new Label, whenever the Submit button is pressed. What you have to do is to create the display Label outside the function and configure its text, whenever the button is pressed. Something like this.
l1 = Label(root, text="", width=200)
l1.pack(side='bottom', padx=50, pady=50)
def display():
ImageVerification(pathlist[0], pathlist[1])
l1.configure(text=Scriptoutput)
#Scriptoutput is the output variable from the main code.
submit_button = Button(text="Submit", width=15,command = display)
submit_button.pack(side='bottom', padx=15, pady=15)

I cant generate a random number and print it

I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()

Python Tkinter StringVar only displaying Py_Var(number)

I am using Tkinter in python 3.4 to make a text based game, and I cannot figure out how to get a string from an Entry widget, it just returns Py_Var#, # being a number. I have looked at answers to similar questions, but none of them quite line up with what I need and have. Here's the relevant pieces of code:
from tkinter import *
win = Tk()
win.geometry("787x600")
playername = StringVar()
def SubmitName():
playername.get
#messagebox.showinfo("Success", playername)
print(playername)
frame3 = Frame(win)
frame3.pack()
label1 = Label(frame3, text="You awaken in a room, with no memories of yourself or your past. ")
label2 = Label(frame3, text="First, how about you give yourself a name:")
label1.config(font=("Courier", 11))
label2.config(font=("Courier", 11))
entry1 = Entry(frame3, textvariable=playername)
entry1.config(font=("Courier", 11))
label1.grid(row=0, column=0, columnspan=3)
label2.grid(row=1, column=0)
entry1.grid(row=1, column=1)
bnamesub= Button(frame3, text="Submit", command=lambda: SubmitName())
bnamesub.grid()
win.mainloop()
Also, first time using stackoverflow and its reading weird but w/e.
You have two mistakes in SubmitName().
First, you need to get the text like this:
txt = playername.get()
Then you need to print that txt:
print(txt)
By mistake you printed the StringVar variable itself.
from tkinter import *
import pickle
win = Tk()
win.geometry("787x600")
def SubmitName():
playername = entry1.get()
messagebox.showinfo("Success", playername)
print(playername)
frame3 = Frame(win)
frame3.grid()
label1 = Label(frame3, text="You awaken in a room, with no memories of yourself or your past. ")
label2 = Label(frame3, text="First, how about you give yourself a name:")
label1.config(font=("Courier", 11))
label2.config(font=("Courier", 11))
#name entered is a StringVar, returns as Py_Var7, but I need it to return the name typed into entry1.
entry1 = Entry(frame3)
entry1.config(font=("Courier", 11))
label1.grid(row=0, column=0, columnspan=3)
label2.grid(row=1, column=0)
entry1.grid(row=1, column=1)
bnamesub= Button(frame3, text="Submit", command=lambda: SubmitName())
bnamesub.grid()
What I changed:
-deleted playername = StringVar(). We don't really need it;
-changed inside the function: changed playername.get to playername = entry1.get();
-added frame3.grid() (without geometry managment, widgets cannot be shown on the screen.);
-also, a little edit: in Python, comments are created with # sign. So I changed * to #.
I was happy to find a solution here, but all these answers "as it is" are not working with my setting, python3.8, pycharm 2018.2
So if anyone could answer this, it seems that entry1.get() cannot be used as a string. I first wanted to append it in a list, and I did a more simple version to point out the trouble :
from tkinter import *
import pickle
win = Tk()
win.geometry("300x300")
#playername = StringVar()
def SubmitName():
labell = Label(win, text="Little tryup").grid()
playername = entry1.get()
# result about line 11: 'NoneType' object has no attribute 'get'
labelle = Label(win, text=playername).grid()
# print(txt)
label1 = Label(win, text="Enter a name:").grid()
entry1 = Entry(win).grid()
boutonne = Button(win, text="label-it!", command=lambda: SubmitName())
boutonne.grid()
win.mainloop()

Categories