tkinter mutliplying the price from table - python

I am making a simple program for cafe management system that reads food names as a buttons from a table also I want to read the the food price from the table and multiply it by the number of button clicks and then save them into a Text how I can do this please
this is the image that show where are the two main isues are
from tkinter import *
from tkinter import ttk
import sqlite3
import time
import datetime
import random
variable = 1
bttn_clicks=0
button_dict = {}
button_dic = {}
conn = sqlite3.connect('hoteldb.db')
c = conn.cursor()
def showqurec():
global button,data2
data2 = readqurec()
for index, dat in enumerate(data2):
button= ttk.Button(master, text=dat[0],command=lambda dat=dat:update_count(dat))
button.grid(row=index+1, column=0,padx=0, pady=0)
button_dict[dat] = button
def showqado():
global button,data2
data2 = readqado()
for index, dat in enumerate(data2):
button = ttk.Button(master, text=dat[0],command=lambda dat=dat: update_count(dat))
button.grid(row=index+1, column=1,pady=0,padx=0)
button_dict[dat] = button
def showcasho():
global button,data2
data2 = readcasho()
for index, dat in enumerate(data2):
button=ttk.Button(master, text=dat[0],command=lambda dat=dat:update_count(dat))
button.grid(row=index+1, column=2,padx=0, pady=0)
button_dict[dat] = button
def readfromdatabase():
cur.execute("SELECT qureec.name,qado.name,casho.name FROM qureec,qado,casho")
return cur.fetchall()
def readqurec():
cur.execute("SELECT name FROM qureec ")
return cur.fetchall()
def readqado():
cur.execute("SELECT name FROM qado ")
return cur.fetchall()
def readcasho():
cur.execute("SELECT name FROM casho ")
return cur.fetchall()
def update_count(x):
global bttn_clicks,my_text,price
my_text=StringVar()
for name in data2:
my_text = button_dict[x].cget('text')
bttn_clicks += 1
def Receipt():
txtReceipt.delete("1.0", "4.0")
x = random.randint(10908, 500876)
randomRef = str(x)
Receipt_Ref.set("BILL" + randomRef)
txtReceipt.insert("1.0", 'Receipt Ref: \t\t\t'+Receipt_Ref.get()+"\t\t"+DateofOrder.get()+"\n")
txtReceipt.insert("2.0", 'Items\t\t'+'Quantity\t\t\t'+"Price \n\n")
if variable !=0:
txtReceipt.insert(END, str(my_text)+'\t\t'+str(bttn_clicks)+'\t\t\t'+""+str(bttn_clicks*3)+"\n")
master=Tk()
master.geometry('630x350+100+200')
master.title('Records')
Label = Button(master, text="meal", width=10,command=showqurec)
Label.grid(row=0, column=0)
BMILabel = Button(master, text="tea", width=10,command=showqado)
BMILabel.grid(row=0, column=1)
stateLabel = Button(master, text="fast food", width=10,command=showcasho)
stateLabel.grid(row=0, column=2)
lblReceipt = Button(master,text="Get Receipt:",anchor='w',command=Receipt)
lblReceipt.grid(row=0,column=4,sticky=W)
txtReceipt = Text(master,bg="white",width=47,height=17.5)
txtReceipt.grid(row=1,column=4,rowspan=4,columnspan=40)
Receipt_Ref=StringVar()
DateofOrder = StringVar()
master.mainloop()
Now I declared the prices but how I can get them from database
I also have another of buttons clicks are incrementing on every buttons clicked how on specied button

Getting the name on the buttons instead of just the first letter you have to set the name to the whole string, not just the first position:
button = ttk.Button(master, text=dat, command ...
(instead of dat[0])
for each of the categories: meal, tea and fast food.
I'm not getting a clear picture of how you want this to work in the end. Do you want the receipt to be updated for each product or only in the end. The function update_count() looks very strange.
I would recommend using a dict to store products and prices. This will make price lookup easy. As long as the application if fairly small I think a global variable would be preferrable.
products = {'Soup': 2.40, 'Fish': 3.10, 'Beef': 3.55, 'Pizza': 2.70}
Take a look at the example code below, try to run it and think about how you want the rest to work. Should the receipt be updated each time you push a button? Should the receipt be ordered in any way? What if you want to remove something from the receitp?
from tkinter import *
from tkinter import ttk
#import sqlite3
import time
import datetime
import random
variable = 1
bttn_clicks=0
button_dict = {}
button_dic = {}
#conn = sqlite3.connect('hoteldb.db')
#c = conn.cursor()
products = {} # Dictionary of products and prices
tally = [] # List of ordered products
def showqurec():
global button, data2
data2 = readqurec()
for index, dat in enumerate(data2):
button = ttk.Button(master, text=dat, command=lambda dat=dat: update_count(dat))
button.grid(row=index+1, column=0, padx=0, pady=0)
button_dict[dat] = button
def showqado():
global button, data2
data2 = readqado()
for index, dat in enumerate(data2):
button = ttk.Button(master, text=dat, command=lambda dat=dat: update_count(dat))
button.grid(row=index+1, column=1, pady=0, padx=0)
button_dict[dat] = button
def showcasho():
global button, data2
data2 = readcasho()
for index, dat in enumerate(data2):
button = ttk.Button(master, text=dat, command=lambda dat=dat: update_count(dat))
button.grid(row=index+1, column=2,padx=0, pady=0)
button_dict[dat] = button
def readfromdatabase(): # This function is never called...
return None
def readqurec(): # Get Meal from database
meal = {'Soup': 2.40, 'Fish': 3.10, 'Beef': 3.55, 'Pizza': 2.70}
products.update(meal)
return meal
def readqado(): # Get Tea from database
tea = {'Tea': 1.20, 'Coffee': 1.00, 'Soda': 1.65}
products.update(tea)
return tea
def readcasho(): # Get Fast food from database
fast_food = {'Hamburger': 1.80,'Hot dog': 1.45,'Pasta': 1.65}
products.update(fast_food)
return fast_food
def update_count(x):
global bttn_clicks,my_text,price
purchase = [x,products[x]] # Get the product and price
tally.append(purchase) # Add this purchase to the tally
print(purchase)
# Leaving the rest of the function as is ...
my_text=StringVar()
for name in data2:
my_text = button_dict[x].cget('text')
bttn_clicks += 1
def Receipt():
txtReceipt.delete("1.0", "4.0")
x = random.randint(10908, 500876)
randomRef = str(x)
Receipt_Ref.set("BILL" + randomRef)
txtReceipt.insert("1.0", 'Receipt Ref: \t\t\t'+Receipt_Ref.get()+"\t\t"+DateofOrder.get()+"\n")
txtReceipt.insert("2.0", 'Items\t\t'+'Quantity\t\t\t'+"Price \n\n")
if variable !=0:
txtReceipt.insert(END, str(my_text)+'\t\t'+str(bttn_clicks)+'\t\t\t'+""+str(bttn_clicks*3)+"\n")
master=Tk()
master.geometry('630x350+100+200')
master.title('Records')
Label = Button(master, text="meal", width=10,command=showqurec)
Label.grid(row=0, column=0)
BMILabel = Button(master, text="tea", width=10,command=showqado)
BMILabel.grid(row=0, column=1)
stateLabel = Button(master, text="fast food", width=10,command=showcasho)
stateLabel.grid(row=0, column=2)
lblReceipt = Button(master,text="Get Receipt:",anchor='w',command=Receipt)
lblReceipt.grid(row=0,column=4,sticky=W)
txtReceipt = Text(master,bg="white",width=47,height=17.5)
txtReceipt.grid(row=1,column=4,rowspan=4,columnspan=40)
Receipt_Ref=StringVar()
DateofOrder = StringVar()
master.mainloop()

Related

Python GUI App is not functioning well, help me fix it?

Here's my code of a gui app using tkinter library, it creats tables and prints orders for each table and gives the ability to edit orders on every table. the goal of it to know what did each table order. but editing the orders doesn't seem to work at all, I need help fixing it.
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
if self.orders_label.select_present():
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
selected_text = self.orders_label.selection_get()
num_newlines = selected_text.count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
orders[order_index] = new_order
self.refresh_label()
def remove_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
num_newlines = self.orders_label.get(start_index, end_index).count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
orders.pop(order_index)
self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
I tried to make it print a label and make it editable using "edit order" button, but the button itself doesn't seem to work, and I want it to print "Empty" if the table has no orders how can i do that.
Look in edit_order and remove_order function. Must easier to write less coding.
Here is code:
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.table_list.get(index)
print(index)
order = orders
self.orders_label.configure(text=order)
#if self.orders_label.select_present():
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#selected_text = self.orders_label.selection_get()
#num_newlines = selected_text.count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
#orders[order_index] = new_order
#self.refresh_label()
def remove_order(self):
remove_orders = self.table_list.curselection()
self.table_list.delete(remove_orders)
self.orders_label.configure(text="")
#index = self.table_list.curselection()[0]
#orders = self.tables[index]
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#num_newlines = self.orders_label.get(start_index, end_index).count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#orders.pop(order_index)
#self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
Result when executes:
Result when selected:
Result when removed order:

how to make a button with a different number in tkinter

im trying to name a button what it is named in ent and so it doesn't repeat when the button is pressed again so if you press once it's button1 and again button2
from tkinter import *
def ext():
win1.destroy()
but1 = Button(root, text=txt.get(), height=10, width=30)
but1.grid(padx=3, row=0, column=1)
def create():
global win1
global txt
win1 = Tk()
win1.geometry("200x200")
ent = Entry(win1)
ent.pack(pady=20)
txt = ent.get()
sub = Button(win1, text="Submit", command=ext)
sub.pack()
root = Tk()
root.geometry("750x750")
root.config(background="#6673ED")
create_but = Button(root, text="Create new card", height=10, width=30, command=create)
create_but.grid(row=0,column=0)
root.mainloop()
The code below uses a dictionary of lists to add an integer to any repeating text input. I think this is what the question is about.
import tkinter as tk # import as tk is safer and more flexible
# Globals to keep it simple
names = {} # Dictionary. Will become a dictionary of lists.
row = 1
col = 0
win1 = None
ent = None
def add_text( txt ):
""" Adds txt to the names dictionary if it doesn't already exist.
Adds and integer to the txt if it does already exit """
name = names.get( txt, None )
if name:
name.append( txt + str(len( name )) ) # Append `txt + int` to a list
else:
names[ txt ] = [ txt ] # Add a list of one item to the dict.
# print( names ) # Uncomment to see what is happening.
return names[ txt ][-1]
def ext():
global row, col
txt = ent.get() # Get the text from the entry
win1.destroy() # before the window is destroyed
txt = add_text( txt )
but1 = tk.Button(root, text=txt, height=10, width=30)
but1.grid(padx=3, row=row, column=col) # row and column need to
# change to show all buttons.
col += 1
if col > 2:
row += 1
col = 0
def create():
global win1
global ent
win1 = tk.Toplevel() # Create a second window with tk.Toplevel.
# Never create two tk.Tk objects.
win1.geometry("200x200")
ent = tk.Entry(win1)
ent.pack(pady=20)
ent.focus() # Position the focus in the Entry
# txt = ent.get() # removed as the Entry was being read before data was entered.
# The entry is now read in `ext`.
sub = tk.Button( win1, text="Submit", command=ext )
sub.pack()
root = tk.Tk()
root.geometry("750x750")
root.config(background="#6673ED")
create_but = tk.Button(root, text="Create new card", height=10, width=30, command=create)
create_but.grid(row=0,column=0)
root.mainloop()

How do I delete or edit records from data base

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))

How To Save a key to a dictionary forever?

iam trying to make a phonebook using python and tkinter . I need to add new numbers to my phonebook
by adding elements to the dictionary but i can't access the numbers again after the programme is closed .
from tkinter import*
#defining the submit button
def submit():
global my_dict
new = entry2.get()
new2 = entry3.get()
my_dict.update({new:new2})
#definig the add button
def add():
top = Toplevel(root)
top.configure(background="black")
top.geometry("400x400")
top.title("Add new member")
label6 =Label(top,text="Welcome",bg="black",fg="orange")
label6.place(x=135,y=13)
global entry2
entry2 = Entry(top,width=23)
entry2.place(x=102,y=78)
label7 = Label(top,text="Name",bg="black",fg="orange")
label7.place(x=48,y=78)
global entry3
entry3 = Entry(top,width = 23)
entry3.place(x=108,y=127)
label8 = Label(top,text="phone number",bg ="black",fg="orange")
label8.place(x=0,y=129)
button3 = Button(top,text="Submit",command = submit)
button3.place(x=185,y=200)
button5 = Button(top,text = "close",command = top.quit)
button5.place(x=185,y=300)
#defining the chek button
def check():
person = entry.get()
if person in my_dict:
phone = my_dict.get(person)
print("Found: " + person + " : " + phone)
# Erase the old result by placing a blank label
label0 = Label(root, width=200, bg ="black", fg = "black").place(x=10,y=167)
label5 = Label(root, text = person + " : " + phone, bg ="black", fg = "orange").place(x=10,y=167)
#creating the main window
root = Tk()
global my_dict
my_dict = {"john":'7598769587'}
root.title("vole phone book")
root.geometry("400x400")
root.configure(background="black")
label = Label(root,text="phone book",bg="black",fg="orange",width=13).place(x=133,y=23)
label2 = Label(root,text="Enter here.",bg = "black",fg="orange").place(x=2,y=89)
entry = Entry(root,width = 27)
entry.place(x=89,y=90)
button =Button(root,text="Check",bg="yellow",fg="red",command=check).place(x=190,y=129)
button2=Button(root,text="Add",width=23,command = add).place(x=120,y=300)
root.mainloop()
this is my code,what to do?
Variables in Python are not saved to disk, they only exist in memory (RAM) unless you explicitly save it there yourself.
You can either save to a file directly or, use a database instead.
See Here for using Pickle to do what you want.

How get value from Tkinter Var in class?

I'm trying to put old school sequential Tkinter code into class structure code.
So let's consider this example :
import Tkinter as Tk
def StartProcess():
print Text_1_Var.get(), Text_2_Var.get(), Text_3_Var.get()
if __name__ == '__main__':
MainFrame = Tk.Tk()
Tk.Button(MainFrame , text = "Start",command=StartProcess).grid(column=2, row=0)
Tk.Label(MainFrame , text = "1").grid(column=1, row=1)
Text_1_Var = Tk.StringVar()
Text_1 = Tk.Entry(MainFrame , width=40, textvariable = Text_1_Var).grid(column=2, row=1)
Tk.Label(MainFrame , text = "2").grid(column=1, row=2)
Text_2_Var = Tk.StringVar()
Text_2 = Tk.Entry(MainFrame , width=40, textvariable = Text_2_Var).grid(column=2, row=2)
Tk.Label(MainFrame , text = "3").grid(column=1, row=3)
Text_3_Var = Tk.StringVar()
Text_3 = Tk.Entry(MainFrame , width=40, textvariable = Text_3_Var).grid(column=2, row=3)
# etc
MainFrame.mainloop()
On press "Start" it displays values of Entry from 1 to 3.
Now i recode it as follow :
import Tkinter as Tk
def StartProcess():
print "???"
class NewEntry(Tk.Frame):
def __init__(self,master=None,idnumber=None):
Tk.Frame.__init__(self,master)
self.pack(side=Tk.TOP)
self.CreateWidgets(idnumber)
def CreateWidgets(self,idnumber):
Tk.Label(master=self, text = idnumber).grid(column=1, row=0)
self.Text_Var = Tk.StringVar()
self.Text = Tk.Entry(master=self, width=40, textvariable = self.Text_Var).grid(column=2, row=0)
if __name__ == '__main__':
MainFrame = Tk.Tk()
Tk.Button(master=MainFrame,text="Start", command=StartProcess).pack()
for i in range (1, 4): # or more
NewEntry(master=MainFrame,idnumber=str(i))
MainFrame.mainloop()
GUI are both identical. I want to get the same result but i don't know where my function StartProcess should take place and how extract value of each self.Text_Var instance.
It's not enough to create a NewEntry object; you need to save references to them so you can access them later (e.g., from StartProcess).
entries = []
for i in range (1, 4): # or more
e = NewEntry(master=MainFrame,idnumber=str(i))
entries.append(e)
# Or more simply,
# entries = [NewEntry(master=MainFrame, idnumber=str(i)) for i in range(1,4)]
Then, StartProcess becomes something like
def StartProcess():
strings = [x.Text_Var.get() for x in entries]
print " ".join(strings)

Categories