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,
I apologize in advance for my bad English...
I am new in the programming world so I don't really know what I'm doing. I'm trying to make a basic address book in Python, Tkinter. I managed somehow to write code to add records in the database but cannot write it to delete or edit selected records. Help would be appreciate
import datetime
import tkinter
from tkinter import *
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import sqlite3
def date_for_humans():
date = datetime.datetime.now().date()
date = str(date)
x = date.split("-")
return x[2] + "." + x[1] + "." + x[0] + "."
# creating windows for show contact
def add():
kontakti = Toplevel()
kontakti.title("Lista kontakta")
kontakti.iconbitmap(r"phonebookicon.ico")
kontakti.geometry("400x500")
kontakti.resizable(False, False)
def submit():
# create data base or connect to one
conn = sqlite3.connect("Imenik.db")
# create cursor
c = conn.cursor()
# insert into a table
c.execute("INSERT INTO Kontakti VALUES (:f_name, :l_name, :number)",
{
"f_name": f_name.get(),
"l_name": l_name.get(),
"number": number.get()
})
# commint changes
conn.commit()
conn.close()
f_name.delete(0,END)
l_name.delete(0, END)
number.delete(0, END)
# creating and coloring top frame
topframe = tk.Frame(kontakti, height=150, bg="#ffffff")
topframe.pack(fill=X)
# creating and coloring bottom farame
bottomframe = tk.Frame(kontakti, height=350, bg="#34ebeb")
bottomframe.pack(fill=X)
# creating text at the top of app:
text2 = Label(kontakti, text="DODAVANJE KONTAKTA", font="ariel 15 bold", bg="#ffffff", fg="black")
text2.place(x=80, y=20)
# creating close button
button1 = Button(kontakti, text="Zatvori prozor", bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=kontakti.destroy)
button1.place(x=295, y=465)
# create text boxes
f_name = Entry(kontakti, width=30)
f_name.place(x=80, y=200, height=20)
l_name = Entry(kontakti, width=30)
l_name.place(x=80, y=230, height=20)
number = Entry(kontakti, width=30)
number.place(x=80, y=260, height=20)
# create text box labels
f_name_label = Label(kontakti, text="Ime", bg="#34ebeb")
f_name_label.place(x=20, y=200)
l_name_label = Label(kontakti, text="Prezime", bg="#34ebeb")
l_name_label.place(x=20, y=230)
number_label = Label(kontakti, text="Broj", bg="#34ebeb")
number_label.place(x=20, y=260)
# create sumbit button
submint_btn = Button(kontakti, text="Dodaj kontakt", bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=submit)
submint_btn.place(x=40, y=320)
def edit():
c.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",
(new_value_for_f_name, new_value_for_l_name, new_value_for_number, f_name, l_name, number))
conn.commit()
def delete():
f_name = listbox.curselection()[0]
l_name = listbox.curselection()[1]
number = listbox.curselection()[2]
c.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
conn.commit()
def leave():
root.destroy()
# creating a main window:
root = Tk()
root.title("Imenik App")
root.iconbitmap(r"phonebookicon.ico")
root.geometry("650x550")
root.resizable(False, False)
# creating and coloring top frame:
topFrame = tk.Frame(root, height=150, bg="#ffffff")
topFrame.pack(fill=X)
# creating and coloring bottom frame:
bottomFrame = tk.Frame(root, height=500, bg="#34ebeb")
bottomFrame.pack_propagate(False)
bottomFrame.pack(fill=X)
listbox = Listbox(bottomFrame)
listbox.place(x=40, y=40, height=340, width=200)
scrollbar = Scrollbar(bottomFrame)
scrollbar.place(height=340, x=240, y=40)
# Insert elements into the listbox
conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
a = c.execute("SELECT *,oid FROM Kontakti")
records = c.fetchall()
for record in records:
listbox.insert(END, str(record[0]) + " " + str(record[1]))
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
# creating text at the top of app:
text1 = Label(root, text="IMENIK", font="ariel 35 bold", bg="#ffffff", fg="black")
text1.place(x=240, y=40)
# displaying date and time at the top of app:
datel = Label(root, text="Danasnji datum: " + date_for_humans(), font="ariel 10 bold", bg="#ffffff", fg="black")
datel.place(x=450, y=125)
# displaying icon at the top of the app:
image1 = Image.open("phonebook1.png")
image1 = image1.resize((90, 90), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image1)
label1 = tkinter.Label(image=image, bg="#ffffff")
label1.image = image
label1.place(x=80, y=30)
conn.commit()
conn.close()
'''
# create data base or connect to one
conn = sqlite3.connect("Imenik.db")
# create cursor
c = conn.cursor()
# create table
c.execute("""CREATE TABLE kontakti (
first_name txt,
last_name txt,
number integer
)""")
# commint changes
conn.commit()
conn.close()
'''
# adding button 1, add contacts
viewButton = Button(root, text="Dodaj kontakt", pady=10, padx=70, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=add)
viewButton.place(x=380, y=200)
# adding button 2, edit contacts
addButton = Button(root, text="Izmeni kontakt", pady=10, padx=67, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=edit)
addButton.place(x=380, y=260)
# adding button 3, delete contacts
deleteButton = Button(root, text="Obrisi kontakt", pady=10, padx=70, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=delete)
deleteButton.place(x=380, y=320)
# adding button 4, exit button
exitButton = Button(root, text="Izlaz", pady=5, padx=50, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=leave)
exitButton.place(x=505, y=510)
root.mainloop()
If anything is unclear please ask I really need help.
Thanks in advance!
Hi and welcome to Stack Overflow. For you to know which data is selected with the mouse, you can use the following way:
name_of_listbox.curselection()
This will return a list of the contents of the rows currently selected. It gives us a list because there is an option to select multiple rows of data in a ListBox.
You can iterate through each and grab the data out of them.
Store the data in a variable and use them for UPDATE and DELETE commands.
EDIT:
For deleting records:
f_name = listbox.curselection()[0]
l_name = listbox.curselection()[1]
number = listbox.curselection()[2]
c1.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
conn1.commit()
For modifying the values:
c1.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",(new_value_for_f_name,new_value_for_l_name,new_value_for_number, f_name, l_name, number))
conn1.commit()
I quite did not get the way you were selecting first name, last name and number from a single listbox. So I have kept the name of the listbox the same.
You are using literal sql script and basically you can delete and update like below.
An advice ORM (Object Relational Mapping) is more effortless rather than raw query.
For Delete
DELETE <TableName> WHERE Id = <Value>
conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
sql = "DELETE TableName WHERE Id = ?"
id = 1
c.execute(sql, (id,))
For Update
UPDATE <TableName> SET <ColumnName> = <NewValue> WHERE Id = <Value>
conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
sql = "UPDATE TableName SET ColumnName = ? WHERE Id = ?"
id = 1
new_value = 'hello'
# params order left to right (important).
c.execute(sql, (new_value, id))
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()
I am creating a Data finder using a db file and i use tkinter entry. however in the console it returns the output [] and the code is this
import sqlite3
import tkinter
db = sqlite3.connect ('covidjakartadb.db')
window = tkinter.Tk()
window.geometry("500x300")
label = tkinter.Label(window, text="Please enter a area")
label.pack()
entry = tkinter.Entry(window)
entry.pack()
select_all = "SELECT * FROM locations WHERE '%{0}%'".format(entry)
cursor = sqlite3.Cursor(db)
cursor.execute(select_all)
def Search_Completed():
label = tkinter.Label(window, text="aaaaa")
Button = tkinter.Button(window, text="Search data", command=Search_Completed)
Button.pack()
positive = cursor.fetchall()
print (positive)
window.mainloop()
This project is due today so a answer today would be greatful
The code to select from the database needs to be in the search_completed function. As written it runs before the GUI is even open.
The search should be using the contents of the Entry, entry.get() not entry.
import sqlite3
import tkinter
db = sqlite3.connect ('covidjakartadb.db')
window = tkinter.Tk()
window.geometry("500x300")
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 * FROM locations WHERE '%{0}%'".format( entry.get() )
# This will work
select_all = "SELECT * FROM locations WHERE City LIKE '%{0}%'".format( entry.get() )
# Or this.
# select_all = "SELECT * FROM locations WHERE City == '{0}'".format( entry.get() )
cursor = sqlite3.Cursor(db)
cursor.execute(select_all)
positive = cursor.fetchall()
print (positive)
label = tkinter.Label(window, text="aaaaa")
Button = tkinter.Button(window, text="Search data", command=Search_Completed)
Button.pack()
window.mainloop()
I'm unable to test the code as I don't have the database so this may have a few errors in 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()