have getting confused in getting the value from the Tkinter() Entry Field. I have this kind of code...
def login():
root_login = Tk()
root_login.title("Login")
root_login.geometry("400x400")
label_text_name = Label(root_login, text="Type mail your :")
label_text_name.pack()
label_text_name.place(x=25, y=50)
label_text_token = Label(root_login, text="Type Pasword :" )
label_text_token.pack()
label_text_token.place(x=58, y=150)
input_text_email = Entry(root_login, width=30)
input_text_email.pack()
input_text_email.place(x=150, y=50)
input_text_token = Entry(root_login, width=30)
input_text_token.pack()
input_text_token.place(x=150, y=150)
e1 = Entry(root_login)
e1.pack()
btn_login = Button(root_login,command=after_login, text="Login", height=1, width=10 )
btn_login.pack()
btn_login.place(x=50, y=250)
def after_login():
var = e1.get()
messagebox.showinfo(var1)
but i get a error !
var = e1.get()
NameError: name 'e1' is not defined
This is because your after_login function doesn't know what e1 is, since it's defined outside of the functions scope. You have to modify your code, maybe by setting the variable as global ( Which can lead to other problems if done incorrectly ) or some other way let after_login know what an e1 is ( by maybe giving it as parameter could solve this? )
Jimpsoni, I have put in a global vatable like this:
def login():
root_login = Tk()
root_login.title("Login")
root_login.geometry("400x400")
label_text_name = Label(root_login, text="Type mail your :")
label_text_name.pack()
label_text_name.place(x=25, y=50)
label_text_token = Label(root_login, text="Type Pasword :" )
label_text_token.pack()
label_text_token.place(x=58, y=150)
input_text_email = Entry(root_login, width=30)
input_text_email.pack()
input_text_email.place(x=150, y=50)
input_text_token = Entry(root_login, width=30)
input_text_token.pack()
input_text_token.place(x=150, y=150)
global var1
var1 = input_text_token.get()
btn_login = Button(root_login,command=after_login, text="Login", height=1, width=10 )
btn_login.pack()
btn_login.place(x=50, y=250)
def after_login():
messagebox.showinfo(var1)
but now I get this error!
global var1
^
IndentationError: unindent does not match any outer indentation level
I found the answer:
def callback():
print(email.get())
....
..
e = Entry(root, bd=1, textvariable=email, validate="focusout" , validatecommand=callback).grid(column=1, row=1)
Related
I am trying to make a program that once the tick box is ticked it then the fields for the email appear but when it is un-ticked then the fields disappear when you press Update.
but I keep on getting:
emailLabel.destroy()
UnboundLocalError: local variable 'emailLabel' referenced before assignment
Any suggestions?, here is my code below:
#so when you tick the box, the value is 1 so this checks for that and sets a equal to 1
#if the box isnt ticked then it checks a and if it is equal to 1 then it
#deletes the fields for the email and code.
#PLEASE HELP. Error is in this bit
def update(var1):
global signupas
global a
print(a)
checklist = var1.get()
print(checklist)
if checklist == 1:
a= 1
if a == checklist:
# // but it's referenced here:
global email
emailLabel = Label(signupas, text="Email")
emailLabel.grid(row=3, column=0)
email = StringVar()
emailEntry = Entry(signupas, textvariable=email)
emailEntry.grid(row=3, column=1)
codeLabel = Label(signupas, text="code")
codeLabel.grid(row=4, column=0)
code = StringVar()
codeEntry = Entry(signupas, textvariable=email)
codeEntry.grid(row=4, column=1)
#its on about this bit:
if a == 1 and checklist == 0:
emailLabel.destroy()
codeLabel.destroy()
signupas.mainloop()
#//this gets the information for the update as it checks for the check box
#//error isn't here but above so don't worry about signup().
def signup():
global signupas
signupas = tk.Toplevel()
signupas.geometry('300x200')
tkWindow.title("database program")
usernameLabel = Label(signupas, text="Username").grid(row=0, column=0)
username = StringVar()
usernameEntry = Entry(signupas, textvariable=username).grid(row=0, column=1)
passwordLabel = Label(signupas,text="Password").grid(row=1, column=0)
password = StringVar()
passwordEntry = Entry(signupas, textvariable=password, show='*').grid(row=1, column=1)
var1 = IntVar()
Checkbutton(signupas, text="2step verification", variable=var1).grid(row=2)
SignUp = partial(checkuser_email, username, password, var1)
updates = partial(update, var1)
updateButton = Button(signupas, text="Update", command=updates).grid(row=5, column=2)
signupButton = Button(signupas, text="SignUp", command=SignUp).grid(row=5, column=1)
signupas.mainloop()
Thanks in advance :)
l would like to create a control system for administrator on Tkinter and some functions (add, delete, update and load) are main part of control system but when l run the code , these functions do not work and there is no error message. But ,l could not figure out where the problem is. My code is still not completed yet. İf l solve it, then l will move to another step.
import tkinter
from tkinter import *
userlist = [
['Meyers', '12356'],
['Smith','abcde'],
['Jones','123abc34'],
['Barnhart','12//348'],
['Nelson','1234'],
["Prefect",'1345'],
["Zigler",'8910'],
['Smith','1298']]
def domain():
def whichSelected () :
print ("At %s of %d" % (select.curselection(), len(userlist)))
return int(select.curselection()[0])
def addEntry():
userlist.append ([nameVar.get(), passwordVar.get()])
setSelect()
def updateEntry():
userlist[whichSelected()] = [nameVar.get(), passwordVar.get()]
setSelect()
def deleteEntry():
del userlist[whichSelected()]
setSelect()
def loadEntry():
name, password = userlist[whichSelected()]
nameVar.set(name)
passwordVar.set(password)
def makeWindow():
win=Tk()
global nameVar, passwordVar, select
frame1 = Frame(win)
frame1.pack()
Label(frame1, text="Name").grid(row=0, column=0, sticky=W)
nameVar = StringVar()
name = Entry(frame1, textvariable=nameVar)
name.grid(row=0, column=1, sticky=W)
Label(frame1, text="Password").grid(row=1, column=0, sticky=W)
passwordVar= StringVar()
password= Entry(frame1, textvariable=passwordVar)
password.grid(row=1, column=1, sticky=W)
frame2 = Frame(win) # Row of buttons
frame2.pack()
b1 = Button(frame2,text=" Add ",command=addEntry)
b2 = Button(frame2,text="Update",command=updateEntry)
b3 = Button(frame2,text="Delete",command=deleteEntry)
b4 = Button(frame2,text=" Load ",command=loadEntry)
b1.pack(side=LEFT); b2.pack(side=LEFT)
b3.pack(side=LEFT); b4.pack(side=LEFT)
frame3 = Frame(win) # select of names
frame3.pack()
scroll = Scrollbar(frame3, orient=VERTICAL)
select = Listbox(frame3, yscrollcommand=scroll.set, height=6)
scroll.config (command=select.yview)
scroll.pack(side=RIGHT, fill=Y)
select.pack(side=LEFT, fill=BOTH, expand=1)
return win
def setSelect():
userlist.sort()
select.delete(0,END)
for name in userlist:
select.insert(END,name)
win=makeWindow()
setSelect()
win.mainloop()
page1=Tk()
but1=Button(page1,text="Domain",command=domain).pack()
It is bad practice to define your functions in a function and makes debugging pretty difficult. I would start by using an object to create this GUI. Object variables:
passwordVar and nameVar,
select
userlist
win
There's a lot going wrong for your code.
For instance, you don't need to import tkinter twice. Your casing of the variable names doesn't follow PEP8. You could benefit from an OOP approach.
I would suggest finding a good IDE to code in that can highlight your formatting and errors.
Take a look at the provided code:
import tkinter as tk
user_list = [
['Meyers', '12356'],
['Smith','abcde'],
['Jones','123abc34'],
['Barnhart','12//348'],
['Nelson','1234'],
["Prefect",'1345'],
["Zigler",'8910'],
['Smith','1298']]
class Domain(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.name_var = tk.StringVar()
self.password_var = tk.StringVar()
self.make_window()
def which_selected(self):
print("At %s of %d" % (self.select.curselection(), len(user_list)))
return int(self.select.curselection()[0])
def add_entry(self):
user_list.append([self.name_var.get(), self.password_var.get()])
self.set_select()
def update_entry(self):
user_list[self.which_selected()] = [
self.name_var.get(), self.password_var.get()]
self.set_select()
def delete_entry(self):
del user_list[self.which_selected()]
self.set_select()
def load_entry(self):
name, password = user_list[self.which_selected()]
self.name_var.set(name)
self.password_var.set(password)
def make_window(self):
frame1 = tk.Frame(self.parent)
frame1.pack()
tk.Label(frame1, text="Name").grid(row=0, column=0, sticky=tk.W)
name = tk.Entry(frame1, textvariable=self.name_var)
name.grid(row=0, column=1, sticky=tk.W)
tk.Label(frame1, text="Password").grid(row=1, column=0, sticky=tk.W)
password = tk.Entry(frame1, textvariable=self.password_var)
password.grid(row=1, column=1, sticky=tk.W)
frame2 = tk.Frame(self.parent) # Row of buttons
frame2.pack()
b1 = tk.Button(frame2, text=" Add ", command=self.add_entry)
b2 = tk.Button(frame2, text="Update", command=self.update_entry)
b3 = tk.Button(frame2, text="Delete", command=self.delete_entry)
b4 = tk.Button(frame2, text=" Load ", command=self.load_entry)
b1.pack(side=tk.LEFT)
b2.pack(side=tk.LEFT)
b3.pack(side=tk.LEFT)
b4.pack(side=tk.LEFT)
frame3 = tk.Frame(self.parent) # select of names
frame3.pack()
scroll = tk.Scrollbar(frame3, orient=tk.VERTICAL)
self.select = tk.Listbox(frame3, yscrollcommand=scroll.set, height=6)
scroll.config(command=self.select.yview)
scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.select.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
def set_select(self):
user_list.sort()
self.select.delete(0, tk.END)
for name in user_list:
self.select.insert(tk.END, name)
if __name__ == '__main__':
root = tk.Tk()
Domain(root)
root.mainloop()
Note:
There's still errors here, but I don't exactly know what you're trying to do so I've just restructured it here so you can start on a better path.
Im working on this python code with tkinter. I would like to change the state of label set_hour to "active" by pressing 'j'. Everytime i run my code i get an error saying that set_hour is not defined. Do I need to use "self" here? and why can you explain please. Thank you
class SetClock:
def __init__(self, parent):
self.myParent = parent
self.current_datetime_label = tkinter.Label(root, text=datetime.datetime.now(), bg = "black", foreground="white").grid(row=1)
#current_time_label.pack()
self.menu_label = tkinter.Label(root, text="Menu", bg="sky blue", foreground="black",width=18).grid(row=2)
self.set_day = tkinter.Label(root, text="Set Day", bg="blue",foreground="white",width=9,state="active").grid(row=2, column=1)
self.set_hour = tkinter.Label(root, text="Set Hour",bg="blue",foreground="white",width=9).grid(row=2, column=2)
self.set_mintutes = tkinter.Label(root, text="Set Minutes", bg="blue",foreground="white",width=10).grid(row=2, column=3)
self.exit_label = tkinter.Label(root, text="Exit", bg="black", foreground="white").grid(row=2, column=4)
self.day_menu_label = tkinter.Label(root, text="Day",bg="sky blue",width=18).grid(row=3)
#menu_label.pack(side="right")
#current_time_label.pack()
def navigate_menu(event):
current_pressed = str(event.char)
print("pressed", current_pressed)
if current_pressed is 'j':
print("ok")
set_hour.config(state="active")
root = Tk()
#frame = Frame(root)
setclock = SetClock(root)
root.title("Set Clock")
root.minsize(width=500,height=500)
root.bind("<Key>",SetClock.navigate_menu)
root.mainloop()
You need to define navigate_menu as an instance method:
def navigate_menu(self, event):
current_pressed = str(event.char)
print("pressed", current_pressed)
if current_pressed is 'j':
print("ok")
self.set_hour.config(state="active")
When you bind it, pass bound method instead:
root.bind("<Key>", setclock.navigate_menu)
Also, separate Label creation line and grid() line. Otherwise, self.set_hour become None because grid() method return None.
self.set_hour = tkinter.Label(root, text="Set Hour",bg="blue",foreground="white",width=9)
self.set_hour.grid(row=2, column=2)
grid() returns None so you have to do
self.set_hour = tkinter.Label(...)
self.set_hour.grid(...)
I'm building a python GUI and there I got 2 text boxes.
I want to create a submit button that will take the data from those 2 text boxes and send them to start(save_place, website_url) function.
This is what I got so far:
from Tkinter import *
def start(save_place, website_url):
#something
app = Tk()
top_app = Frame(app)
top_app.pack()
save_location = Entry(top_app, width=20)
url = Entry(top_app, width=20)
save_location.grid(sticky=W, row=0)
url.grid(sticky=W, row=1)
save_place = save_location.get("1.0", END)
website_url = url.get("1.0", END)
button_start = Button(top_app, text="Start", fg="green", command=start(save_place,website_url))
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
I also tried this:
from Tkinter import *
def start():
save_place = save_loc.get()
website_url = urls.get()
print (save_place + " " + website_url)
app = Tk()
top_app = Frame(app)
top_app.pack()
save_loc = StringVar()
save_location = Entry(top_app, textvariable=save_loc, width=85)
urls = StringVar()
url = Entry(top_app, textvariable=urls, width=85)
button_start = Button(top_app, text="Start", fg="green", command=start)
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
And it didn't work.
How can I make this script send the inputs in the text boxes to the function?
Thanks to all the helpers :)
As mentioned in the previous response "about how to call a function", you just put command = start and put save_place = save_location.get()
in start function, however you can use save_location = Entry(top_app, width=20), so the total prg:
from Tkinter import *
def start():
#something
save_place = save_location.get()
website_url = url.get()
print save_place,website_url
app = Tk()
top_app = Frame(app)
top_app.pack()
save_location = Entry(top_app, width=20)
url = Entry(top_app, width=20)
save_location.grid(sticky=W, row=0)
url.grid(sticky=W, row=1)
button_start = Button(top_app, text="Start", fg="green", command=start)
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
command=start(save_place,website_url) doesn't do what you think its doing. It's assigning the result of the function call to the command. (Which is probably None). Bind your Entry boxes to StringVar like:
location = StringVar()
Entry(top_app, textvariable=location, width=20)
Then you assign the function call to the command parameter using command = start. Inside the function you can access the value in the Entry using location.get(). To set the value use the corresponding method location.set(value)
So I've written a python script that uses the PIL library to format a png passed to it. I want to make the script more user friendly and after looking around I saw the Tkinter library which seemed perfect. Basically the script has five variables that I need to pass to it for it to run. I'm currently using the raw_input() function to asking the user for the following variables:
path_to_png
title
subtitle
source
sample_size
Once received the script runs and exports the formatted png. I've used Tkinter to build those basic inputs as you can see from the picture below but I don't know how to pass the inputed text values and the file path from the choose png button to their respective variables.
from Tkinter import *
from tkFileDialog import askopenfilename
from tkMessageBox import *
app = Tk()
app.title("Picture Formatting")
app.geometry('500x350+200+200')
#
def callback():
chart_path = askopenfilename()
return
def title_data():
title_data = chart_title
return
errmsg = 'Error!'
browse_botton = Button(app, text="Choose png", width=15, command=callback)
browse_botton.pack(side='top', padx=15, pady=15)
# Get chart data
chart_title = StringVar()
title = Entry(app, textvariable = chart_title)
title.pack(padx=15, pady=15)
chart_subtitle = StringVar()
subtitle = Entry(app, textvariable = chart_subtitle)
subtitle.pack(padx=15, pady=15)
chart_source = StringVar()
source = Entry(app, textvariable = chart_source)
source.pack(padx=15, pady=15)
chart_sample_size = IntVar()
sample_size = Entry(app, textvariable = chart_sample_size)
sample_size.pack(padx=15, pady=15)
submit_button = Button(app, text="Submit", width=15)
submit_button.pack(side='bottom', padx=15, pady=15)
app.mainloop()
I have tried your code, and I added some lines:
from Tkinter import *
from tkFileDialog import askopenfilename
from tkMessageBox import *
app = Tk()
app.title("Picture Formatting")
app.geometry('500x350+200+200')
#
def callback():
global chart_path
chart_path = askopenfilename()
return
def title_data():
title_data = chart_title
return
def calculate():
chart_title = title.get()
chart_subtitle = subtitle.get()
chart_source = source.get()
chart_sample_size = sample_size.get()
print "chart_path : ", chart_path
print "chart_title : ", chart_title
print "chart_subtitle : ", chart_subtitle
print "chart_source : ", chart_source
print "chart_sample_size : ", chart_sample_size
#Call your functions here
return
errmsg = 'Error!'
# Get chart data
chart_path = ''
browse_botton = Button(app, text="Choose png", width=15, command=callback)
browse_botton.pack(side='top', padx=15, pady=15)
chart_title = StringVar()
title = Entry(app, textvariable = chart_title)
title.pack(padx=15, pady=15)
chart_subtitle = StringVar()
subtitle = Entry(app, textvariable = chart_subtitle)
subtitle.pack(padx=15, pady=15)
chart_source = StringVar()
source = Entry(app, textvariable = chart_source)
source.pack(padx=15, pady=15)
chart_sample_size = IntVar()
sample_size = Entry(app, textvariable = chart_sample_size)
sample_size.pack(padx=15, pady=15)
submit_button = Button(app, text="Submit", width=15, command=calculate)
submit_button.pack(side='bottom', padx=15, pady=15)
app.mainloop()
I think the problem you want to ask is how to get the text values in the entry widgets and get the path text from the askopenfilename() function. You can use the method Entry.get() to get the text value in certain entry widget.
And you can just use str = askopenfilename() to get the path's text value. But because this line of code is written in a function, you need to declare that it is a global variable or create a class to contain them, or the interpreter will consider that variable is an local variable and it will not be passed to the function calculate() which I added.
Since you didn't use a class to contain the variables, I also use the variables as global variables. It is not a good design. You can consider to create a class instead.
In order to receive the value from an entry widget, you would want to use the get() function. The get() function will return whatever is in the entry widget. For instance in your case: response = sample_size.get() will set the variable response to 0. See this page for more documentation on the entry widget.
Hope this helped.