Trying to delete the the entry widget with a button but keep getting the error
AttributeError: 'object' object has no attribute 'delete'
I shortened my code to:
from tkinter import *
e = object()
def getname():
global name
e = Entry(root, textvariable=name)
e.pack()
e.focus_set()
b = Button(root, text = "Get", width = 10, command = callback)
b.pack()
b2 = Button(root, text = "Delete", width = 10, command = delete_entry)
b2.pack()
def callback():
username = name.get()
print(username)
def delete_entry():
e.delete(0, "end")
root = Tk()
name = StringVar()
getname()
root.mainloop()
Thanks for your time
You can use this code ( which delete the Entry box totally):
def delete_entry():
e.destroy()
Or do you only want to delete the text within the Entry widget? Tell me and I will update my answer.
Related
I am trying to make a little thing in python like JOpenframe is java and I'm trying to make an entry box. That works fine but when I try to get the value and assign it to variable "t" nothing works. This is what I have:
def ButtonBox(text):
root = Tk()
root.geometry("300x150")
t = Label(root, text = text, font = ("Times New Roman", 14))
t.pack()
e = Entry(root, borderwidth = 5, width = 50)
e.pack()
def Stop():
root.destroy()
g = e.get()
ok = Button(root, text = "OK", command = Stop)
ok.pack()
root.mainloop()
t = ButtonBox("f")
I've tried to make "g" a global variable but that doesn't work. I have no idea how to get the value from this, and I'm hoping someone who does can help me out. Thanks!
If you want to return the value of the entry box after ButtonBox() exits, you need to:
initialize g inside ButtonBox()
declare g as nonlocal variable inside inner function Stop()
call g = e.get() before destroying the window
Below is the modified code:
from tkinter import *
def ButtonBox(text):
g = "" # initialize g
root = Tk()
root.geometry("300x150")
t = Label(root, text = text, font = ("Times New Roman", 14))
t.pack()
e = Entry(root, borderwidth = 5, width = 50)
e.pack()
def Stop():
# declare g as nonlocal variable
nonlocal g
# get the value of the entry box before destroying window
g = e.get()
root.destroy()
ok = Button(root, text = "OK", command = Stop)
ok.pack()
root.mainloop()
# return the value of the entry box
return g
t = ButtonBox("f")
print(t)
class Login:
def __init__(self):
Label1 = Label(root,text = "Username")
Label2 = Label(root,text = "Password")
self.Entry1 = Entry(root)
self.Entry2 = Entry(root,show = "*")
Label1.grid(row=0)
Label2.grid(row=1)
self.Entry1.grid(row = 0,column = 1)
self.Entry2.grid(row = 1,column = 1)
root.minsize(width = 300,height = 80)
##new_window_button = Button(text="new window", command = ????)
##new_window_button.grid(columnspan = 2)
lgbutton = Button(text = "Login",command = self.ButtonClicked)
lgbutton.grid(columnspan = 2)
def ButtonClicked(self):
username = self.Entry1.get()
password = self.Entry2.get()
GetDatabase(username,password)
Currently this is what I have to create a window, however I want it to that when the new_window_button is clicked, the new page has its own widgets. I've used Toplevel before but it creates a child window without the widgets. Instead, the widgets are added to the parent window.
Judging by the comments it looks as though you are struggling with declaring the correct parent for widgets.
When a widget is declared the first parameter passed in to it is it's parent. For example:
Label(root, text="I'm in the root window.")
# ^ This is the parent
As opposed to:
Label(top, text="I'm in the top window.")
# ^ This is the parent
Please see a more fleshed out example below:
from tkinter import *
root = Tk()
top = Toplevel(root)
label1 = Label(root, text="I'm a placeholder in your root window.")
label2 = Label(top, text="I'm a placeholder in your top window.")
label1.pack()
label2.pack()
root.mainloop()
import tkinter
from tkinter import *
class LoginForm(Frame):
def __init__(self,master=None):
super().__init__(master)
self.pack()
self.createWidget()
def createWidget(self):
self.lblEmailId=Label(self,text="Email Id")
self.lblEmailId.grid(row=0,column=0)
self.varEmailid=StringVar()
self.txtEmailId=Entry(self,textvariable=self.varEmailid)
self.txtEmailId.grid(row=0,column=1)
self.txtEmailId.bind("<KeyRelease>",self.key_press)
self.lblPassword = Label(self, text="Password")
self.lblPassword.grid(row=1, column=0)
self.varPassword=StringVar()
self.txtPassword= Entry(self, textvariable=self.varPassword)
self.txtPassword.grid(row=1, column=1)
self.btnLogin=Button(self,text="Login")
self.btnLogin.grid(row=2,column=1)
self.btnLogin.bind("<Button-1>",self.btnLogin_click)
def btnLogin_click(self,event):
self.varPassword.set(self.varEmailid.get())
LoginWindow=Toplevel()
def key_press(self,event):
self.varPassword.set(self.varEmailid.get())
root=Tk()
fromLogin=LoginForm(root)
root.mainloop()
Im trying to create a Python tkinter login registeration but running into a small issue.
The error message is:
self.Label_Name = Label(top, text="What is your username: ")
AttributeError: Label instance has no __call__ method
Please can you proof read my code:
from Tkinter import *
class Register:
def __init__(self, parent):
top = self.top = Toplevel(parent)
# Variables to store the entries
self.VarEntUser = StringVar()
self.VarEntPass = StringVar()
self.VarEntRetype = StringVar()
self.Label_Name = Label(top, text="What is your username: ")
self.Label_Password = Label(top, text="Enter a password: ")
self.Label_Retype = Label(top, text="Retype Password: ")
# Entry fields for the user to enter there details
self.Ent_Name = Entry(top, textvariable=self.VarEntUser)
self.Ent_Password = Entry(top, textvariable=self.VarEntPass)
self.Ent_Retype = Entry(top, textvariable=self.VarEntRetype)
# Puts all the fields ^, into the window
self.Label_Name.grid(row=0, sticky=W)
self.Label_Password.grid(row=1, sticky=W)
self.Label_Retype.grid(row=2, sticky=W)
self.Ent_Password.grid(row=1, column=1)
self.Ent_Retype.grid(row=2, column=1)
self.Ent_Name.grid(row=0, column=2)
# Run the RegisterCheck function
# submit button which Checks the Entered details then writes the user and pass to a .txt file
self.MySubmitButton = Button(top, text='Submit', command=RegisterCheck)
self.MySubmitButton.pack()
self.U = raw_input(self.VarEntUser.get())
self.P = raw_input(self.VarEntPass.get())
self.R = raw_input(self.VarEntRetype.get())
class LogIn:
def __init__(self, parent):
top = self.top = Toplevel(parent)
self.a = StringVar()
self.b = StringVar()
self.Label_Log_User1 = Label(top, text='Username:')
self.Label_Log_Pass = Label(top, text='Password: ')
self.Ent_User_Log = Entry(top, textvariable=self.a)
self.Ent_Pass_Log = Entry(top, textvariable=self.b)
self.Label_Log_User1.grid(row=1)
self.Pass_Log.grid(row=2)
self.EntUserLog.grid(row=1, column=1)
self.EntPassLog.grid(row=2, column=1)
self.User = raw_input(self.EntUserLog.get())
self.Pass = raw_input(self.EntUserLog.get())
# runs the 'LoginCheck' function
self.LogInButton = Button(top, text="Log In", command=LogInCheck)
self.LogInButton.pack()
def LogInCheck(self):
# Checks if the fields are blanking displaying an error
if len(self.User) <= 0 and len(self.Pass) <= 0:
print "Please fill in all fields."
else:
pass
# Checks to see if the user and pass have been created
if self.User in 'username.txt' and self.Pass in 'password':
print 'You are now logged in!'
else:
print "Log in Failed"
def RegisterCheck(self):
# Checks if the fields are blank
if len(self.P) <= 0 and len(self.U) <= 0:
print "Please fill out all fields."
else:
pass
# Check is the password and the retype match
if self.P == self.R:
pass
else:
print "Passwords do not match"
# After registering write the user and pass to a .txt file
with open('username.txt', 'a') as fout:
fout.write(self.U + '\n')
with open('password.txt', 'a') as fout:
fout.write(self.P + '\n')
# Depending on what the user chooses, either log in or register than opens the specific window
def launch_Register():
inputDialog = Register(root)
root.wait_window(inputDialog.top)
def launch_LogIn():
inputdialog2 = LogIn(root)
root.wait_window(inputdialog2.top)
root = Tk()
label = Label(root, text='Choose an option')
label.pack()
loginB = Button(root, text='Log In', command=launch_LogIn)
loginB.pack()
registerB = Button(root, text='Register', command=launch_Register)
registerB.pack()
root.mainloop()
The problem is that in this line
Label = Label(root, text='Choose an option')
you define a Label called Label, thus shadowing the Label constructor. Then, then you create the several labels in your Register and Login classes (triggered by those two buttons), the name Label is no longer bound to the constructor, but to that specific label.
Change the name of the label, then it should work. Also, I would advise you to use lower-case names for variables and methods. This alone might help prevent many such errors.
root = Tk()
label = Label(root, text='Choose an option')
label.pack()
loginB = Button(root, text='Log In', command=launch_LogIn)
loginB.pack()
registerB = Button(root, text='Register', command=launch_Register)
registerB.pack()
root.mainloop()
Note that there are a few many more problems with your code:
StringVar a and b should probably be self.a and self.b
You are trying to use raw_input to get the user input in the Entry widgets; this is wrong! Instead, just read the value of the variables to get the values, e.g. instead of self.User, use self.a.get()
do not mix grid and pack layout
if self.User in 'username.txt' will not check whether that name is in that file
loginCheck and registerCheck should be methods of the respective class
Once I'm at it, here's (part of) my version of your code, to help you getting started:
class Register:
def __init__(self, parent):
top = self.top = Toplevel(parent)
self.var_user = StringVar()
self.var_pass = StringVar()
self.var_retype = StringVar()
Label(top, text="What is your username: ").grid(row=0, sticky=W)
Label(top, text="Enter a password: ").grid(row=1, sticky=W)
Label(top, text="Retype Password: ").grid(row=2, sticky=W)
Entry(top, textvariable=self.var_user).grid(row=0, column=1)
Entry(top, textvariable=self.var_pass).grid(row=1, column=1)
Entry(top, textvariable=self.var_retype).grid(row=2, column=1)
Button(top, text='Submit', command=self.registerCheck).grid(row=3)
def registerCheck(self):
u, p, r = self.var_user.get(), self.var_pass.get(), self.var_retype.get()
if p and u:
if p == r:
logins[u] = p
else:
print "Passwords do not match"
else:
print "Please fill out all fields."
class LogIn:
# analogeous to Register; try to figure this out xourself
def launch_Register():
inputDialog = Register(root)
root.wait_window(inputDialog.top)
def launch_LogIn():
inputDialog = LogIn(root)
root.wait_window(inputDialog.top)
logins = {}
root = Tk()
Label(root, text='Choose an option').pack()
Button(root, text='Log In', command=launch_LogIn).pack()
Button(root, text='Register', command=launch_Register).pack()
root.mainloop()
Note that I changed the login "database" from files to a dictionary to keep things simple and to focus on the Tkinter problems. Of course, neither a simple dictionary nor a plain-text file is an appropriate way to store login information.
Also, I put the creation and the layout of the GUI widgets on one line. In this case this is possible since we do not need a reference to those widgets, but beware never to do e.g. self.label = Label(...).grid(...), as this will bind self.label to the result of grid, and not to the actual Label.
Finally, this will still print all the messages to the standard output. Instead, you should add another Label for that, or open a message dialogue, but this is left as an excercise to the reader...
When I type in entrybox1 it automatically appears in entrybox2. So is like anything that happens entrybox1 happens to entrybox2.
Below is my code
from Tkinter import*
import random
class Love:
def __init__(self):
window = Tk()
window.title("Love Calculator")
window.geometry("300x180")
frame1 = Frame(window)
frame1.pack()
self.lbl = Label(frame1, text = "Love is Pure",fg="white",bg = "blue")
self.lbl2=Label(frame1, text ="are you meant for one another",fg="White",bg = "red")
self.lbl3=Label(frame1,text="Let FIND OUT!!",fg="white",bg = "green")
self.lbl.pack()
self.lbl2.pack()
self.lbl3.pack()
frame2=Frame(window)
frame2.pack()
label = Label(frame2,text = "Your Name")
label2 = Label(frame2, text= "Your Lovers name")
self.msg = StringVar
entry1 = Entry(frame2, textvariable =self.msg)
self.out = StringVar
entry2 = Entry(frame2, textvariable =self.out)
btCalculate=Button(frame2, text="Calculate", command=self.processButton)
label.grid(row=1,column=1)
label2.grid(row=2,column=1)
entry1.grid(row=1,column=2)
entry2.grid(row=2,column=2)
btCalculate.grid(row=4,column=3,sticky=E)
Both of your Entry widgets are effectively using the same textvariable. This is because you are using StringVar wrong. You aren't creating newStringVars, you're merely referencing the class.
In short, you need to do this:
self.msg = StringVar()
... Rather than this:
self.msg = StringVar
Notice the use of ().
In the following code, I have been trying to disable the entry1 widget every time I select 1 in the combobox and disable entry2 when i select 2 in combobox.
this is my code:
from Tkinter import *
import ttk
def refresh():
if v.get() == 'A':
entry1.state(['disabled'])
entry2.state(['!disabled'])
elif v.get() == 'B':
entry2.state(['disabled'])
entry1.state(['!disabled'])
root = Tk()
v = StringVar()
var = StringVar()
entry1 = ttk.Entry (root, textvariable= var)
entry1.grid(row=2, column=2, sticky=(E,W))
entry2 = ttk.Entry (root, textvariable= var)
entry2.grid(row=4, column=2, sticky=(E,W))
v_list=['A','B']
v.set(v_list[1])
v_optionmenu = apply(OptionMenu, (root,v) + tuple(v_list))
v_optionmenu.grid(column=4,row=11,sticky=(W,E))
var = v
root.bind('<Return>', lambda e: refresh)
root.mainloop()
I wanted to create condition based enabling and disabling of widgets.
My conditions usually are:
selection in combobox
Selection of radiobutton
Please Advice how i can go about it.
The piece you seem to be missing is that you can change the state with the configure method. Also, you can set a trace on a variable to have a function called when the value changes. Since you said you want to change the state based on a combobox, that is the technique you would use. You can do a similar trick with a radiobutton, though radiobuttons also have a command option which can be used instead of a trace.
Here's an example showing how to trigger a "refresh" function when a combobox changes:
import Tkinter as tk
import ttk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.choiceVar = tk.StringVar()
self.e1 = ttk.Entry(self)
self.e2 = ttk.Entry(self)
self.cb = ttk.Combobox(self, textvariable=self.choiceVar,
values=["Enable 1 only", "Enable 2 only"])
self.cb.set(self.cb.cget("values")[0])
self.cb.pack(side="top")
self.e1.pack(side="top")
self.e2.pack(side="top")
self.choiceVar.trace("w", self.on_trace_choice)
self.refresh()
def on_trace_choice(self, name, index, mode):
self.refresh()
def refresh(self):
choice = self.cb.get()
if choice == "Enable 1 only":
self.e1.configure(state="normal")
self.e2.configure(state="disabled")
else:
self.e1.configure(state="disabled")
self.e2.configure(state="normal")
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
def refresh(*args):
if v.get() == 'Disable' :
fb_entry.state(['disabled'])
fw_entry.state(['disabled'])
fb.set('')
fw.set('')
elif v.get() == 'Enable' :
fb_entry.state(['!disabled'])
fw_entry.state(['!disabled'])
root = Tk()
v = StringVar()
var = StringVar()
entry1 = ttk.Entry (root, textvariable= var)
entry1.grid(row=2, column=2, sticky=(E,W))
entry2 = ttk.Entry (root, textvariable= var)
entry2.grid(row=4, column=2, sticky=(E,W))
v_list=['Disable','Enable']
v.set(v_list[1])
v_optionmenu = apply(OptionMenu, (root,v) + tuple(v_list))
v_optionmenu.grid(column=4,row=11,sticky=(W,E))
var = v
root.bind('<Enter>',refresh_widget)
root.mainloop()