Am trying to append the value of radiobutton selected before printing the content in the entry field but am able to append the content in the entry widget to csv file. I would appreciate any help on how to go around achieve that.
from tkinter import *
import csv
with open ("profile.csv", "w") as db:
writer = csv.writer(db)
writer.writerow(["NAME ", "GENDER"]) # create with heading
def save_details():
global e1 # global variable to receive the data from entry
data = e1.get()
#Sex = R1.get
# Sex = R2.get()
totalinput = [ data] # Sex here to append to the csv file
with open("profile.csv", "a") as savedb:
w = csv.writer(savedb)
w.writerow(totalinput)
def validate():
value = option.get() # this for radiobutton
now = new.get() # this for an entry widget
if value != "male" and value != "female":
print("An option must be selected")
else:
print(now)
root = Tk()
root.geometry("400x400")
new = StringVar()
e1 = Entry(root, textvariable=new)
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option,
command=save_details, indicatoron=0)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option,
command=save_details, indicatoron=0)
button = Button(root, text="OK", command=validate)
e1.pack()
R1.pack()
R2.pack()
button.pack(side="bottom")
root.mainloop()
Replace:
data = e1.get()
with:
data = option.get()
Radiobuttons share a variable that based on Radiobuttons' state that variable updates its value.
In your case option's value is "male" if R1 is selected and "female" if R2 is selected, as in option.get() returns "male" or "female".
For completeness bind your save_details() and validate function to the OK button.Then add you value to the totalinput list totalinput = [ data, Sex] to append both to the file.
from tkinter import *
import csv
with open ("profile.csv", "w") as db:
writer = csv.writer(db)
writer.writerow(["NAME ", "GENDER"]) # create with heading
def save_details():
global e1 # global variable to receive the data from entry
data = e1.get()
Sex = option.get() # this will get the value of radio selected and append it to the file
totalinput = [ data, Sex] # Sex here to append to the csv file
with open("profile.csv", "a") as savedb:
w = csv.writer(savedb)
w.writerow(totalinput)
def validate():
value = option.get() # this for radiobutton
now = new.get() # this for an entry widget
if value != "male" and value != "female":
print("An option must be selected")
else:
print(now)
root = Tk()
root.geometry("400x400")
new = StringVar()
e1 = Entry(root, textvariable=new)
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option, indicatoron=0)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option, indicatoron=0)
button = Button(root, text="OK", command=lambda :[save_details(), validate()])
e1.pack()
R1.pack()
R2.pack()
button.pack(side="bottom")
root.mainloop()
Related
I cannot load a checkbox value from a file and have it correctly check the checkbox when the value is 1.
With the code below you can check a box and save it to a file. Clicking Load will load that value into a second variable, convert it to Int and create a checkbox linked to its value, but it will never generate already checked, even when the value of it's variable is 1 as shown by the print command. What am I doing wrong?
Window = Tk()
var = IntVar()
LoadVarTemp = 0
LoadVar = IntVar()
def SaveIt():
YesVar = var.get()
with open("config.txt", "w") as configfile:
configfile.write(str(YesVar))
def LoadIt():
with open("config.txt") as file:
content = file.readlines()
content = [x.strip() for x in content]
LoadVarTemp = content[0]
LoadVar = int(LoadVarTemp)
print(LoadVar)
Checkbutton(Window, text="Loaded", variable=LoadVar).grid(row=1)
YesCheck = Checkbutton(Window, text="Yes?", variable = var).grid(row=0)
SaveButton = Button(Window, text="Save", command=SaveIt).grid(row=2)
LoadButton = Button(Window, text="Load", command=LoadIt).grid(row=3)
Window.mainloop()
Ok, so basic story. I have created an entry. After you introduce text, you have to click a button to store the inputted text into a variable that is later printed.
Here is the code:
from Tkinter import *
def myClick(entry_name, var):#defines function to get input from entry and store into var
var = entry_name.get()
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
hello = None #variable to store entry input
bt1 = Button(root, command = myClick(ent, hello))#button 1 creation and function attribution
bt1.grid(row = 3, column = 0)#button 1 griding
root.mainloop()
print(hello)
It is very unclear to me why the function does not get the input from the entry.
bt1 = Button(root, command = myClick(ent, hello))
In this line, you call myClick function with parameters, not just pass it. That means that myClick is executed once after the module is launched and then it does nothing. If you want to print the entry input, I recommend you do the following:
from tkinter import *
root = Tk()
lbl1 = Label(root, text="hello")
lbl1.grid(row=0, column=0)
ent = Entry(root, width=15)
ent.grid(row=1, column=0)
def myClick():
var = ent.get()
print(var)
bt1 = Button(root, command=myClick)
bt1.grid(row=3, column=0)
root.mainloop()
Also code after root.mainloop() doesn't excecute.
just define a normal function :
from tkinter import *
def blinta():
var = ent.get()
ent.delete(0,END)
print(var)
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
bt1 = Button(root, command = blinta)
bt1.grid(row = 3, column = 0)
root.mainloop()
This will work I'm sure.
My Problem is described in these following steps:
1. Opened Application
2. Typed name = Mike ; id = 11 ; url = www.google.com
3. Clicked on "Add"
4. Closed the application.
5. Again Run the application.
6. Shows "Mike = 11" in the list box.
7. But when I select "Mike = 11" and click on "load" , it does not take me to "www.google.com", Why?
Please give me some solutions about how can I open a URL attaching with saved list.
Please HELP me!!
from tkinter import*
import webbrowser
def add():
name = entry1.get()
id = entry2.get()
listbox.insert(END, name+ " : " +id)
def delete():
select = listbox.curselection()
index = select[0]
listbox.delete(index)
def save():
with open("file.txt","w") as f:
for i in listbox.get(0,END):
f.write(i+"\n")
#f.close()
def load():
url = entry3.get()
select=listbox.curselection()
index=select[0]
webbrowser.open(index)
read = open("file.txt","r")
data_list = read.readlines()
read.close()
data_list = [data.rstrip() for data in data_list]
win = Tk()
win.title("Class")
frame1=Frame(win)
frame2=Frame(win)
frame1.pack()
frame2.pack()
label1 = Label(frame1,text="Name : ")
label1.grid(row=0,column=0)
label2 = Label(frame1,text="Id : ")
label2.grid(row=1,column=0)
label3 = Label(frame1,text="Url : ")
label3.grid(row=2,column=0)
name = StringVar()
entry1 = Entry(frame1,textvariable=name)
entry1.grid(row=0,column=1)
id = StringVar()
entry2 = Entry(frame1,textvariable=id)
entry2.grid(row=1,column=1)
url = StringVar()
entry3 = Entry(frame1,textvariable=url)
entry3.grid(row=2,column=1)
scrollbar = Scrollbar(frame2,orient=VERTICAL)
listbox = Listbox(frame2,selectmode=EXTENDED,yscrollcommand=scrollbar.set,width=60)
listbox.pack()
scrollbar.config(command=listbox)
for item in data_list:
listbox.insert(END,item)
button1 = Button(frame2,text="Add",command=add)
button1.pack()
button2 = Button(frame2,text="Delete",command=delete)
button2.pack()
button3 = Button(frame2,text="Save to File",command=save)
button3.pack()
button4 = Button(frame2,text="Load Url",command=load)
button4.pack()
win.mainloop()
You need to use two list.one list saves data in the file,this could be seen in the Listbox.The another list is to save the url in the file.this couldn't be seen.And also you need to synchronize them.(save(),delete(),add() need to operate both Listbox widget and the list).A minimal example.:
from tkinter import*
import webbrowser
def add():
name = entry1.get()
id = entry2.get()
url = entry3.get()
url_list.append(url)
listbox.insert(END, name+ " : " +id)
def delete():
select = listbox.curselection()
index = select[0]
url_list.pop(index)
listbox.delete(index)
def save():
with open("file.txt","w") as f:
for i,j in zip(listbox.get(0,END),url_list):
f.write(f"{i} Url:{j}\n")
def load():
select=listbox.curselection()
index=select[0]
load_url = url_list[index]
webbrowser.open(load_url)
read = open("file.txt","r")
data_url_list = read.readlines()
read.close()
data_list = [data.rstrip().split("Url")[0] for data in data_url_list]
url_list = [data.rstrip().split("Url:")[1] for data in data_url_list]
win = Tk()
win.title("Class")
frame1=Frame(win)
frame2=Frame(win)
frame1.pack()
frame2.pack()
label1 = Label(frame1,text="Name : ")
label1.grid(row=0,column=0)
label2 = Label(frame1,text="Id : ")
label2.grid(row=1,column=0)
label3 = Label(frame1,text="Url : ")
label3.grid(row=2,column=0)
name = StringVar()
entry1 = Entry(frame1,textvariable=name)
entry1.grid(row=0,column=1)
id = StringVar()
entry2 = Entry(frame1,textvariable=id)
entry2.grid(row=1,column=1)
url = StringVar()
entry3 = Entry(frame1,textvariable=url)
entry3.grid(row=2,column=1)
scrollbar = Scrollbar(frame2,orient=VERTICAL)
listbox = Listbox(frame2,selectmode=EXTENDED,yscrollcommand=scrollbar.set,width=60)
listbox.pack()
scrollbar.config(command=listbox)
for item in data_list:
listbox.insert(END,item)
button1 = Button(frame2,text="Add",command=add)
button1.pack()
button2 = Button(frame2,text="Delete",command=delete)
button2.pack()
button3 = Button(frame2,text="Save to File",command=save)
button3.pack()
button4 = Button(frame2,text="Load Url",command=load)
button4.pack()
win.mainloop()
In this example,the format in the file:
name : id Url:xxxxxx
You also could use another way to save them and read them.
I am creating a program with tkinter which comes with a default name and password stored in a text file. After login you need to open the Toplevel window and type in the name and password you want to use in your subsequent logins. I have defined my variables but if I want to overwrite the text file I receive the below:
Error "NameError: name 'e1' is not defined"
Which I know I have defined.
import sys
from tkinter import messagebox
from tkinter import *
now = open("pass.txt","w+")
now.write("user\n")
now.write("python3")
now.close()
def login_in():
with open("pass.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == name and entry2.get() == password:
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")
def change_login():
ch = Toplevel(root)
ch.geometry('300x300')
e1 = Entry(ch, width=20).pack()
e2 = Entry(ch, width=20).pack()
sb = Button(ch, text="save", command=save_changes).pack()
def save_changes(): # function to change data in the txt file
data = e1.get() + "\n " + e2.get()
with open("pass.txt", "w") as f:
f.writelines(data)
root= Tk()
log = Toplevel()
root.geometry("350x350")
log.geometry("200x200")
entry1 = Entry(log)
entry2 = Entry(log)
button1 = Button(log, text="Login", command=login_in) #Login button
entry1.pack()
entry2.pack()
button1.pack()
label = Label(root, text="welcome").pack()
butt = Button(root, text="change data in file", command=change_login).pack()
root.withdraw()
root.mainloop()
So you have a few options here but in general you have 2 major issues.
The first issue is the use of .pack() after the creation of your e1 and e2 entry fields. This is a problem for the get() method as the geometry manager will return None if you pack this way. The correct method is to create the widget first with e1 = Entry(ch, width=20) and then pack it on the next line with e1.pack() this will allow get() to work on e1.
The second issue is the matter of local variables vs global variables. You have created e1 and e2 inside of the function change_login() and without telling python that e1 and e2 are global variables it will automatically assume you want them as local variables. This means the variables are only accessible from within the function they are created in.
You have a few options and I will break them out for you.
1) The quick and dirty option is to assign e1 and e2 as global variables. This can be done by using global var_name, var2_name, and_so_on so in this case add this line to the top of your change_login(): and save_changes() functions:
global e1, e2
This well tell python to add e1 and e2 to the global name space and it will allow save_changes() to work with the variables in the global name space.
2) Another method is to pass the 2 variables to save_changes() using the button command. We will need to use lambda for this and we can accomplish this by adding:
command = lambda e1=e1, e2=e2: save_changes(e1, e2)
to the button created in change_login() and adding the 2 arguments to save_changes() like this:
save_changes(e1, e2)
This will work just as well as the first option and it also avoids the use of global variables.
3) A third option is to create the entire program as a class and to use class attributes to allow the variables to work with all methods within the class.
Below is an example of your code using the 1st option:
import sys
from tkinter import messagebox
from tkinter import *
now = open("pass.txt","w+")
now.write("user\n")
now.write("python3")
now.close()
def login_in():
with open("pass.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == name and entry2.get() == password:
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")
def change_login():
global e1, e2
ch = Toplevel(root)
ch.geometry('300x300')
e1 = Entry(ch, width=20)
e1.pack()
e2 = Entry(ch, width=20)
e2.pack()
sb = Button(ch, text="save", command=save_changes).pack()
def save_changes(): # function to change data in the txt file
global e1, e2
data = e1.get() + "\n" + e2.get() # removed space after \n
with open("pass.txt", "w") as f:
f.writelines(data)
root= Tk()
log = Toplevel()
root.geometry("350x350")
log.geometry("200x200")
entry1 = Entry(log)
entry2 = Entry(log)
button1 = Button(log, text="Login", command=login_in) #Login button
entry1.pack()
entry2.pack()
button1.pack()
label = Label(root, text="welcome").pack()
butt = Button(root, text="change data in file", command=change_login).pack()
root.withdraw()
root.mainloop()
Below is an example of your code using the 2nd option:
import sys
from tkinter import messagebox
from tkinter import *
now = open("pass.txt","w+")
now.write("user\n")
now.write("python3")
now.close()
def login_in():
with open("pass.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if entry1.get() == name and entry2.get() == password:
root.deiconify()
log.destroy()
else:
messagebox.showerror("error","login Failed")
def change_login():
ch = Toplevel(root)
ch.geometry('300x300')
e1 = Entry(ch, width=20)
e1.pack()
e2 = Entry(ch, width=20)
e2.pack()
Button(ch, text="save", command=lambda e1=e1, e2=e2: save_changes(e1, e2)).pack()
def save_changes(e1, e2): # function to change data in the txt file
data = e1.get() + "\n" + e2.get() # removed space after \n
with open("pass.txt", "w") as f:
f.writelines(data)
root= Tk()
log = Toplevel()
root.geometry("350x350")
log.geometry("200x200")
entry1 = Entry(log)
entry2 = Entry(log)
button1 = Button(log, text="Login", command=login_in) #Login button
entry1.pack()
entry2.pack()
button1.pack()
label = Label(root, text="welcome").pack()
butt = Button(root, text="change data in file", command=change_login).pack()
root.withdraw()
root.mainloop()
Below is an example of your code converted to a class and using class attributes to avoid the use of global variables.
import sys
from tkinter import messagebox
from tkinter import *
class MyApp(Frame):
def __init__(self, master, *args, **kwargs):
Frame.__init__(self, master, *args, **kwargs)
self.master = master
self.master.withdraw()
self.log = Toplevel()
self.master.geometry("350x350")
self.log.geometry("200x200")
self.entry1 = Entry(self.log)
self.entry2 = Entry(self.log)
self.button1 = Button(self.log, text="Login", command=self.login_in)
self.entry1.pack()
self.entry2.pack()
self.button1.pack()
Label(root, text="welcome").pack()
Button(root, text="change data in file", command=self.change_login).pack()
def login_in(self):
with open("pass.txt") as f:
new = f.readlines()
name = new[0].rstrip()
password = new[1].rstrip()
if self.entry1.get() == name and self.entry2.get() == password:
self.master.deiconify()
self.log.destroy()
else:
messagebox.showerror("error","login Failed")
def change_login(self):
ch = Toplevel(self.master)
ch.geometry('300x300')
self.e1 = Entry(ch, width=20)
self.e1.pack()
self.e2 = Entry(ch, width=20)
self.e2.pack()
Button(ch, text="save", command=self.save_changes).pack()
def save_changes(self):
data = "{}\n{}".format(self.e1.get(), self.e2.get())
with open("pass.txt", "w") as f:
f.writelines(data)
if __name__ == "__main__":
now = open("pass.txt","w+")
now.write("user\n")
now.write("python3")
now.close()
root = Tk()
app = MyApp(root)
root.mainloop()
What I need is to make the view orders button to get the text from the Customer.txt file and set it inside a textfield i made.
#make order,cancel,view
from tkinter import *
import tkinter.messagebox
root = Tk()
file = open("Customer.txt", "w")
def textW():
outFile = open("Customer.txt", "wt")
def CancelOrder():
outFile=open("Customer.txt", "w")
outFile.write("")
tkinter.messagebox.showinfo("Cancel Order", "Your order has been canceled")
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
#tViewOrder.set(test)
print (test)
#test.set(tViewOrder)
#outFile.close()
def MakeOrder():
outFile=open("Customer.txt", "w")
outFile.write("" + tMakeOrder.get())
tkinter.messagebox.showinfo("Make Order", "Order has been placed. Thank you!")
#Labels
lMakeOrder = Label(root, text="Make an order")
lViewOrder = Label(root, text="View Order")
#TextFields
tMakeOrder = Entry(root)
tViewOrder = Entry(root, state="disabled")
#Buttons
bMakeOrder = Button(root, text="Make order",bg="black",fg="green", command=MakeOrder)
bCancelOrder = Button(root, text="Cancel order",bg="black",fg="green", command=CancelOrder)
bViewOrder = Button(root, text="View orders",bg="black",fg="green", command=ViewOrder)
#Position
lMakeOrder.grid(row=0)
lViewOrder.grid(row=1)
tMakeOrder.grid(row=0, column=2)
tViewOrder.grid(row=1, column=2)
bMakeOrder.grid(row=4)
bViewOrder.grid(row=4, column=2)
bCancelOrder.grid(row=4, column=4)
#Window stuff
root.title("Sky is a shit name service - Customer")
root.geometry("300x300")
root.mainloop()
You can put text inside your Entry by calling insert function on it.
MyEntry.insert(POSITION, TEXT)
Oh and one more thing. You can't insert anything in the entry if it's disabled.
So here is your modified function:
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
tViewOrder['state'] = 'normal'
tViewOrder.delete(0, 'end') #Remove everything before
tViewOrder.insert(0, test)
tViewOrder['state'] = 'disabled'
outFile.close()