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.
Related
I want to get a variable from a function to use this variable in another function.
Simple example:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
def printresult():
print(text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
If I press the testbutton and afterwards the printbutton, then I get the error "name 'text' is not defined".
So how am I able to get the text variable from the def test() to use it in the def printresult()?
You need to save the value somewhere well known:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
test.text = text # save the variable on the function itself
def printresult():
print(test.text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
Since you are using tkinter, I'd use a StringVar to store the result. Using a string var makes it easy for other tkinter widgets to use the value.
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text.set(intro + name)
def printresult():
print(text.get())
root = Tk()
root.title("Test")
text = StringVar()
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
I'm trying to create a GUI that allows to the user to manipulate data from mysql database. So the user must add a trip(trip-id, trip-short-name ...) then add stop times for each trip using Entry from tkinter.
paths=''
new_trip_id=''
def add_trip():
top = Toplevel()
top.title("Trips")
top.geometry("600x300")
lbl1 = Label(top, text = 'service_id:', font = {'Helvetica',10})
lbl1.place(relx=0.2, rely=0.1)
entry1 = Entry(top)
entry1.place(relx=0.45, rely=0.1)
global new_trip_id
lbl2 = Label(top, text = 'trip_id:', font = {'Helvetica',10})
lbl2.place(relx=0.2, rely=0.25)
entry2 = Entry(top)
entry2.place(relx=0.45, rely=0.25)
new_trip_id=entry2.get()
lbl3 = Label(top, text = 'trip_headsign')
entry3 = Entry(top)
entry3.place(relx=0.45, rely=0.4)
lbl4 = Label(top, text = 'trip_short_name:', font{'Helvetica',10})
lbl4.place(relx=0.2, rely=0.55)
entry4 = Entry(top)
entry4.place(relx=0.45, rely=0.55)
entry4.bind('<Return>', add_times)
button1 = Button(top, text="Cancel")
button1.place(relx=0.5 ,rely=0.7)
def add_times(event):
mysql.connector("INSERT INTO trips VALUES service_id, trip_id,
trip_headsign, trip_short_name",
[enty1.get(), entry2.get(), enty3.get(),
enty4.get()])
top = Toplevel()
top.title("Trips")
top.geometry("600x300")
Ididn't found a solution that allows to the user to add data.
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 am trying to update information in tkinter labels and buttons without redrawing entire screens. I'm using Python 3, a Raspberry Pi, and Idle. I have a trivial example of what I am trying to do. I see comments here that suggest I need to learn to manipulate stringvariable or IntVar, etc. but my book is totally unhelpful in that regard. In this example, I would like the number between the buttons to track the value of the number as it changes with button pushes.
##MoreOrLess.01.py
from tkinter import *
global number
number = 5
root = Tk()
root.title("Test Buttons")
def Less():
global number
number -= 1
print ("The number is now ", number)
def More():
global number
number += 1
print("The number is now ", number)
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, text = number).pack(pady = 20)
MakeLabel(number)
Not only do you base yourself in a book, check the official documentation of tkinter. in your case you must create a variable of type IntVar with its set() and get() method, and when you want to link that variable through textvariable.
from tkinter import *
root = Tk()
root.title("Test Buttons")
number = IntVar()
number.set(5)
def Less():
number.set(number.get() - 1)
print ("The number is now ", number.get())
def More():
number.set(number.get() + 1)
print("The number is now ", number.get())
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, textvariable = number).pack(pady = 20)
MakeLabel(number)
root.mainloop()
I am new in python and trying to make a program for converting a given string into a secret code. The string entered by user in the text box is taken as input and converted in secret code (using the encryption module). How do I display the result in the window (I tried using the label but it shows an error.)
from tkinter import *
import encryption as En # Loading Custom libraries
import decryption as De
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_box = None
resut_l = None
result_2 = None
def b1_action(): # Encryption button
input_text = text_box.get()
if input_text == "":
print("Text field empty")
else:
En.enc_text(input_text) # Message is returned as 'code'
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
De.dec_text(input_text)
def enc_button(): # Button for rendering encryption
b1 = Button(root, text = "ENCRYPT", font = button1_font, command = b1_action)
b1.configure(bg = 'palegreen3', width = '10', height = '3')
b1.place(x = '120', y = '130')
def dec_button(): # Button for decryption
b2 = Button(root, text = "DECRYPT", font = button2_font, command = b2_action)
b2.configure(bg = 'palegreen3', width = '10', height = '3')
b2.place(x = '340', y = '130')
def main(): #This is the core of GUI
global root
global text_box
root = Tk()
root.geometry("550x350")
root.configure(bg = "MediumPurple1")
win_text = Label(root, text = 'Enter text below and Choose an action:', bg = 'MediumPurple1', font = font_L1)
win_text.place(x = '10', y = '50')
text_box = Entry(root, text = 'Enter the Text', width = 60, bg = 'light blue')
text_box.place(x = '100', y = '100')
inst_text = Label(root, text = instructions, bg = "MediumPurple1", font = font_inst)
inst_text.pack(side = BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
And here is the encryption module
def enc_text(line):
msg = str(line).replace(' ', '_').lower()
msg_list = list(msg)
all_char = list("abcdefghijklmnopqrstuvwxyzabc_!?#")
for i in range(0, len(msg)):
pos_replaced = all_char.index(str(msg_list[i])) #will give the positon of the word to be replaced in the main list of alphabets
msg_list.insert(i, all_char[pos_replaced + 3]) #will replace the elements one by one
msg_list.pop(i + 1)
i += 1
code = ''.join(msg_list).replace('#', ' ')
print(code)
You can also suggest some improvisations.
Part of the problem is that Entry widgets don't have a text= configuration option, so it's completely ignored in the line:
text_box = Entry(root, text='Enter the Text', width=60, bg='light blue')
The best way to handle the character contents of an Entry is by using its textvariable= option and setting the value of it to be an instance of a tkinter.StringVar, then the getting and setting the value of that object will automatically update the Entry widget on the screen.
Below is your code with changes made to it to do this. Note I commented and changed a few unrelated things to be able to run the code, but tried to indicate the most important ones. Also note I added a return code statement at the very end of the enc_text() function in your custom encryption module.
from tkinter import *
import encryption as En # Loading Custom libraries
#import decryption as De # DON'T HAVE THIS.
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_var = None # ADDED.
text_box = None
resut_l = None
result_2 = None
# CHANGED TO USE NEW "text_var" variable.
def b1_action(): # Encryption button
input_text = text_var.get()
if input_text == "":
print("Text field empty")
else:
text_var.set(En.enc_text(input_text))
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
"""De.dec_text(input_text)"""
def enc_button(): # Button for rendering encryption
b1 = Button(root, text="ENCRYPT", font=button1_font, command=b1_action)
b1.configure(bg='palegreen3', width='10', height='3')
b1.place(x='120', y='130')
def dec_button(): # Button for decryption
b2 = Button(root, text="DECRYPT", font=button2_font, command=b2_action)
b2.configure(bg='palegreen3', width='10', height='3')
b2.place(x='340', y='130')
def main(): #This is the core of GUI
global root
global text_box
global text_var # ADDED
root = Tk()
root.geometry("550x350")
root.configure(bg="MediumPurple1")
win_text = Label(root, text='Enter text below and Choose an action:',
bg='MediumPurple1', font=font_L1)
win_text.place(x='10', y='50')
text_var = StringVar() # ADDED
text_var.set('Enter the Text') # ADDED
# CHANGED text='Enter the Text' to textvariable=text_var
text_box = Entry(root, textvariable=text_var, width=60, bg='light blue')
text_box.place(x='100', y='100')
inst_text = Label(root, text="instructions", bg="MediumPurple1",
font=font_inst)
inst_text.pack(side=BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()