Adding to the interface with mongodb data - python

In the picture: I designed an interface with tkinter by pulling data over mongodb. I want it to appear as a mongodb-fed list.
How can I do it.
very uneven like that.
Also, I don't want _id to appear.
the code I wrote:
import pymongo
import tkinter as tk
from tkinter import messagebox
client = pymongo.MongoClient("secure")
koleksiyon = client["dukkan"]
db = koleksiyon["yaglar"]
master = tk.Tk()
master.geometry("300x300")
def buttonCallback():
uruns = tk.Toplevel()
uruns .geometry("300x300")
mas = tk.Label(uruns, text="Urunler listesi")
veriler = db.find().sort("db")
for x in veriler:
urunn = tk.Label(uruns, text=x)
urunn.pack()
mas.pack()
urunler = tk.Button(master, text="Tüm Ürünler", command=buttonCallback)
label_1 = tk.Label(master, text="Bolat Aktar ürün yönetim sistemi")
label_1.grid(row=0, column=0)
urunler.grid(row=1, column=0)
master.mainloop()
How can I list regularly?

Search for Python Dictionaries and f-Strings, and you can edit your code like that:
urunn = tk.Label(uruns, text=f"Marka: {x['urunmarkasi']}, "
f"Adı: {x['urunadi']}, "
f"Boyut: {x['boyut']}, "
f"Fiyat: {x['fiyat']}")

Related

How to make this python currency quote application using API work?

I made two different projects. One using tkinter to make GUI and the other one I was learning to use customtkinter. In this project I'm trying to combine the dollar, euro and bitcoin quote code with what I learned doing GUI using customtkinter. I don't exactly know how to get this to run right now. I've read the customtkinter documentation but I couldn't find the answer. If you can help me I will be grateful haha
import customtkinter
import requests
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")
root = customtkinter.CTk()
root.geometry("500x350")
root.title("Cotacao Krettina")
def pegar_cotacoes():
requisicao = requests.get('https://economia.awesomeapi.com.br/json/last/USD-BRL,EUR-BRL,BTC-BRL')
requisicao_dic = requisicao.json()
cotacao_dolar = requisicao_dic ['USDBRL']['bid']
cotacao_euro = requisicao_dic ['EURBRL']['bid']
cotacao_bitcoin = requisicao_dic ['BTCBRL']['bid']
texto = f'''
Dolar: {cotacao_dolar}
Euro: {cotacao_euro}
Bitcoin: {cotacao_bitcoin}'''
texto_cotacoes["text"] = texto
frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)
button = customtkinter.CTkButton(master=frame, text="Cotar!", command=pegar_cotacoes)
button.pack(pady=12, padx=10)
texto_cotacoes = customtkinter.CTkLabel(master=root, width=120, height=25, corner_radius=8)
texto_cotacoes.pack(pady=12, padx=10)
root.mainloop()\

How to update Tkinter Progressbar?

So I'm writing some code to check VAT-IDs using a web API. Since some files have quite a large amount of API-calls it sometimes takes quite a while to complete and I want to show a progressbar so other users know that the program hasn't crashed yet. I found an example and modified it slightly so that it fits my needs. This code shows a window with a progressbar and once the for loop is finished the window closes.
import tkinter as tk
from tkinter import ttk
import time
def wrap():
MAX = 30000
root = tk.Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = tk.IntVar() #here you have ints but when calc. %'s usually floats
theLabel = tk.Label(root, text="Sample text to show")
theLabel.pack()
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=MAX)
progressbar.pack(fill=tk.X, expand=1)
def loop_function():
k = 0
for k in range(MAX):
### some work to be done
progress_var.set(k)
time.sleep(0.002)
root.update()
root.destroy()
root.after(100, loop_function)
root.mainloop()
wrap()
Now I wanted to implement this into my tool:
import pandas as pd
import re
import pyvat
from tkinter import ttk
import tkinter as tk
def vatchecker(dataframe):
#initialise progressbar
root = tk.Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = tk.DoubleVar() #here you have ints but when calc. %'s usually floats
theLabel = tk.Label(root, text="Calling VAT Api")
theLabel.pack()
maxval = len(dataframe['Vat-ID'])
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=maxval)
progressbar.pack(fill=tk.X, expand=1)
checked =[]
def loop_function():
for row in range(len(dataframe['Vat-ID'])):
print("Vatcheck: " + str(round(row/maxval * 100, 2)) + " %")
if pd.isna(dataframe['Vat-ID'][row]):
checked.append('No Vat Number')
else:
#check if vat id contains country code
groups = re.match(r'[A-Z][A-Z]', dataframe['Vat-ID'][row])
if groups != None:
querystring = dataframe['Vat-ID'][row][:-2]
country = dataframe['Vat-ID'][row][-2:]
#else get VAT-ID from Country ISO
else:
querystring = dataframe['Vat-ID'][row]
country = dataframe['Land-ISO2'][row]
try:
result = pyvat.check_vat_number(str(querystring), str(country))
checked.append(result.is_valid)
except:
checked.append('Query Error')
progress_var.set(row)
root.update()
root.destroy()
root.quit()
root.after(100, loop_function)
root.mainloop()
dataframe['Vat-ID-check'] = checked
return dataframe
This function gets called by the main script. Here the progressbar window is shown yet the bar doesn't fill up.
With print("Vatcheck: " + str(round(row/maxval * 100, 2)) + " %") I can still track the progress but it's slightly ugly.
Earlier in the main script the user already interacts with a Tkinter GUI but afterwards I close those windows and loops with root.destroy()' and 'root.quit() so I think it should be fine to run another Tkinter instance like this?
Any help or hints would be greatly appreciated.
as #jasonharper mentioned above changing progress_var = tk.DoubleVar() to progress_var = tk.DoubleVar(root) works

How to get the selected item in a Python TkInter multiple combobox in a loop?

I would like to create a table similar to Excel's style. It should be depending on the size of the array to show.
For this reason the table columns and rows are inside loop cycles.
In the first line I would have a combobox to select the value to filter.
Also the combobox is inside a loop cycle for the different columns number.
When the table is created I am not able to recognize which combobox is chosen.
How can I do?
Example:
import tkinter
from tkinter import ttk #per button, label etc
from tkinter.ttk import *
import numpy as np #for the matrix tools
def newselection(event, output):
print("Value selected:", event, output)
def ShowTableGui(MatrixToShowIn):
MatrixToShow=np.array(MatrixToShowIn)
RowNumber = MatrixToShow.shape[0]
ArrayCombo=[]
windowx=tkinter.Tk()
windowx.title("Table viewer")
buttonExit = ttk.Button(windowx, text="Close table", command=windowx.destroy)
# buttonExit = ttk.Button(windowx, text="Run Filter", command= lambda: Run_filter(MatrixToShow.shape[1]))
buttonExit.grid(column=0, row=0)
for Col in range (int(MatrixToShow.shape[1])):
ValuesInsert=MatrixToShow[:,Col] # values in column
ValuesInsert=[row[Col]for row in MatrixToShowIn]
ValuesInsert=list(set(ValuesInsert)) # values listed only once
ValuesInsert.sort()
ValuesInsert.insert(0,"*") # add * to filter all
comboExample0 = ttk.Combobox(windowx, state='readonly', values=ValuesInsert)
comboExample0.grid(column=Col+2, row=0)
comboExample0.bind("<<ComboboxSelected>>", lambda event:newselection(comboExample0.get(), "output"))
# comboExample0.bind("<<ComboboxSelected>>", lambda event:newselection(event, "output"))
ArrayCombo.append(comboExample0)
Select=comboExample0.get()
print(Select)
for Row in range (RowNumber):
b = Entry(windowx, text="")
b.grid(row=Row+1, column=Col+2)
b.insert(0,str(MatrixToShow[Row][Col]))
windowx.mainloop()
return()
MatrixToShowIn=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
ShowTableGui(MatrixToShowIn)
Finally I have the time to post the solution found thanks to your help:
from tkinter import *
from functools import partial
from tkinter.ttk import *
class ComboTest:
def __init__(self, MatrixToShow):
self.top = Tk()
self.top.title('Combos Test')
self.top_frame = Frame(self.top, width =400, height=400)
self.button_dic = {}
self.combos_dic = {}
self.var = StringVar()
self.top_frame.grid(row=0, column=1)
Button(self.top_frame, text='Exit',
command=self.top.destroy).grid(row=0,column=0, columnspan=5)
self.combos(MatrixToShow)
self.top.mainloop()
##-------------------------------------------------------------------
def combos(self,MatrixToShow):
b_row=1
Columns=[]
for com_num in range(len(MatrixToShow[0])):
Column=["*"]
for Row in range(len(MatrixToShow)):
Column.append(MatrixToShow[Row][com_num])
Columns.append(Column)
## note that the correct "com_num" is stored
# self.combos_dic[com_num] = "self.cb_combo_%d()" % (com_num)
e = Entry(self.top_frame)
e.insert(0, com_num)
e.insert(0, "Column")
e.grid(row=b_row, column=com_num)
b = Combobox(self.top_frame, state='readonly', values=Column)
b.bind("<<ComboboxSelected>>", partial(self.cb_handler, com_num))
b.current(0)
b.grid(row=b_row+1, column=com_num)
##----------------------------------------------------------------
def cb_handler( self, cb_number, event ):
print ("ComboNumber", cb_number, "SelectedValue", event.widget.get())
##=================================================================
MatrixToShowIn=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
CT=ComboTest(MatrixToShowIn)
Enjoy Roberto

How can I get the option selected by a user from a combobox in toplevel

I'm new to Python and Tkinter and was trying to create an interface to search & plot data. I created a very simple toplevel window to get the values from a combobox that would be selected from users. However, I find the script would only print the first item in the list if comboxlist2.current(0) was set or it would print nothing, no matter which one is selected in the box. I created a sample script to test this. If I click on the "search & create", then the return values can change according to the user selection in comboxlist1, while it would all return "1" no matter what the user selected in comboxlist2. So may I ask where is the issue and how to solve?
Thanks in advance for the potential suggestions or solutions!
import tkinter as tk
from tkinter import ttk
from tkinter import *
def root_print():
reg_in = comboxlist1.get()
print(reg_in) #print the value selected
def on_click():
tl = Toplevel()
comvalue2 = tk.StringVar()
comboxlist2 = ttk.Combobox(tl,textvariable=comvalue2)
comboxlist2["values"] = ("1","2","3")
comboxlist2.grid()
comboxlist2.current(0) #select the first one as default
#mm = comboxlist2.get()
#print(mm) #print directly
go(comboxlist2,tl)
tl.wait_window()
return
def go(comboxlist2,tl):
mm = comboxlist2.get()
Button(tl,text='go', command=lambda:test(mm)).grid()
def test(mm):
print(mm) #do the same thing for the comboxlist2
root = Tk()
root.title('search') #create an interface
root.geometry('+400+200') #size and position
Label(text='region ').grid(row=2,column=0)
comvalue1 = tk.StringVar()
comboxlist1=ttk.Combobox(root,textvariable=comvalue1)
comboxlist1["values"]=("all","africa","asia","australia","canada","europe","mexico","southamerica","usa")
comboxlist1.grid(row=2,column=1)
comboxlist1.current(0)
Button(text='search & create', command=root_print).grid(row=0,column=4)
Button(text='click', command=on_click).grid(row=1, column=4)
loop = mainloop()#go!
Here is the working code, which should take care of your needs. I have removed the imports and some code snippets which are not useful.
import tkinter as tk
from tkinter import ttk
def root_print():
reg_in = comboxlist1.get()
print(reg_in)
def on_click():
tl = tk.Toplevel()
comvalue2 = tk.StringVar()
comboxlist2 = ttk.Combobox(tl,textvariable=comvalue2)
comboxlist2["values"] = ("1","2","3")
comboxlist2.grid()
comboxlist2.current(0) #select the first one as default
tk.Button(tl,text='go', command=lambda: test(comboxlist2.get())).grid()
tl.wait_window()
def test(mm):
print(mm)
root = tk.Tk()
root.title('search') #create an interface
root.geometry('+400+200') #size and position
tk.Label(text='region ').grid(row=2,column=0)
comvalue1 = tk.StringVar()
comboxlist1=ttk.Combobox(root,textvariable=comvalue1)
comboxlist1["values"]=("all","africa","asia","australia","canada","europe","mexico","southamerica","usa")
comboxlist1.grid(row=2,column=1)
comboxlist1.current(0)
tk.Button(text='search & create', command=root_print).grid(row=0,column=4)
tk.Button(text='click', command=on_click).grid(row=1, column=4)
root.mainloop()

How to Dynamically Label my Buttons Based on Database Query using Tkinter

I am trying to label my button dynamically based on the database results. So in this case the button would be labeled '23'
Database
| id | number |
| 1 | 23
from tkinter import *
import pymysql as mdb
from tkinter import ttk
#functions
def functionHolder():
print("do nothing function holder")
root = Tk()
dbi = mdb.connect("localhost",port=3306, user="access", passwd="***", db="index_db" )
cursor = dbi.cursor()
cursor.execute("""SELECT number FROM caution_elements WHERE id = 1 """)
dbi.commit()
data = cursor.fetchone()[0]
dbi.close()
result =str("%s " % data)
varButt = Button(root,textvariable=data, command=functionHolder)
varButt.pack()
root.mainloop()
Button should be labeled [23] I currently get a blank button and no errors
A textvariable option of tkinter widgets require special variable classes such as StringVar, BooleanVar or IntVar. Their values can be accessed using get method and their values can be changed using set as in:
import tkinter as tk
root = tk.Tk()
data = tk.StringVar()
data.set("This")
def change():
if data.get() == "This":
data.set("That")
else:
data.set("This")
tk.Label(root, textvariable=data).pack()
tk.Button(root, text="Change", command=change).pack()
root.mainloop()
If you are not sure about using class variables another example without them would be:
import tkinter as tk
root = tk.Tk()
data = "This"
def change():
global data
if data == "This":
data = "That"
a_label['text'] = data
else:
data = "This"
a_label.config(text=data)
a_label = tk.Label(root, text=data)
a_label.pack()
tk.Button(root, text="Change", command=change).pack()
root.mainloop()
Both of the code pieces do the same thing except that when you change data's value, in the first example you're also changing text displayed by the label, and in the second example you need to explicitly update a_label's text option.
Also note that you can use a_widget.config(option=value), a_widget.configure(option=value), a_widget['option'] = value interchangeably given that you're modifying only one option.

Categories

Resources