from tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.instruction = Label(self, text="Enter password")
self.instruction.grid(row=0, cloumn=0, cloumnspan=2, sticky=W)
self.password = Entry(self)
self.password.grid(row=1, column=1, sticky=W)
self.submit_button = Button(self, text="submit", command=self.reveal)
self.submit_button.grid(row=2, column=0, sticky=W)
self.text = Text(self, width=35, height=5, wrap=WORD)
self.text.grid(row=3, column=0, columnspan=2, sticky=W)
def reveal(self):
content = self.password.get()
if content == "password":
message = "You have access to something special"
else:
message = "Access Denined"
self.text.insert(0.0, message)
root = Tk()
menubar = Menu(root)
root.geometry("450x450+500+300")
root.title("Change Creation")
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Close", command = close)
menubar.add_cascade(label="File", menu=filemenu)
root.title("Password")
root.geometry("250x150")
app = Application(root)
root.mainloop()
while execution of the above code, I'm not getting any prompt or any error.Help me out in finding the solution
You have several indention errors and typos.
I am not sure how you are not getting errors as I had to fix at least 3 errors while trying to run your code. If you are using Python's default IDLE then I would suggest upgrading to something like PyCharm or Eclipse Pydev. They will provide proper traceback errors for debugging.
I have cleaned up you code. Make sure you check spelling. You had cloumn instead of column and cloumnspan instead of columnspan. command = close will cause an error as no method or function exist called close.
from tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.instruction = Label(self, text="Enter password")
self.instruction.grid(row=0, column=0, columnspan=2, sticky=W)
self.password = Entry(self)
self.password.grid(row=1, column=1, sticky=W)
self.submit_button = Button(self, text="submit", command=self.reveal)
self.submit_button.grid(row=2, column=0, sticky=W)
self.text = Text(self, width=35, height=5, wrap=WORD)
self.text.grid(row=3, column=0, columnspan=2, sticky=W)
def reveal(self):
content = self.password.get()
if content == "password":
message = "You have access to something special"
else:
message = "Access Denined"
self.text.insert(0.0, message)
root = Tk()
menubar = Menu(root)
root.geometry("450x450+500+300")
root.title("Change Creation")
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Close")
menubar.add_cascade(label="File", menu=filemenu)
root.title("Password")
root.geometry("250x150")
app = Application(root)
root.mainloop()
Related
I am writing a code for a login system using tkinter and for some reason when I run the code there are no error messages and a window pops up but without the title, buttons or labels I need.
from tkinter import *
import tkinter.messagebox
frame = Tk()
def adminlogincheck(self, master):
frame = Frame(master)
frame.pack()
if username == '123key' and password == 'key123':
accept = Label(frame, text='Login Successful')
else:
decline = Label(frame, text='Login incorrect')
mainloop()
def adminselect(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="Cancel", fg="red", command=quit)
self.button.pack(side=LEFT)
self.slogan = Button(frame, text="Proceed", command=self.adminlogin)
self.slogan.pack(side=LEFT)
mainloop()
def adminlogin(self, master):
frame = Frame(master)
frame.pack()
username_entry = Entry(frame)
password_entry = Entrey(frame)
confirm = Button(frame, text='Login', command = adminlogincheck)
loginquit = Button(frame, text='Cancel', command=quit)
mainloop()
I will add more after the login system works but does anyone know why no buttons or labels appear?
There's enough in your request to see what you're trying to accomplish, but there are many issues with the code. Here is a working model of what you appear to be working toward...
from tkinter import *
import tkinter.messagebox
class Admin:
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
self.username = StringVar()
self.password = StringVar()
def logincheck(self):
self.clearframe()
if self.username.get() == '123key' and self.password.get() == 'key123':
accept = Label(self.frame, text='Login Successful')
accept.pack(side=LEFT)
else:
decline = Label(self.frame, text='Login incorrect')
decline.pack(side=LEFT)
def select(self):
self.clearframe()
self.button = Button(self.frame, text="Cancel", fg="red", command=quit)
self.button.pack(side=LEFT)
self.slogan = Button(self.frame, text="Proceed", command=self.adminlogin)
self.slogan.pack(side=LEFT)
def login(self):
self.clearframe()
username_entry = Entry(self.frame, textvariable=self.username)
username_entry.pack()
password_entry = Entry(self.frame, textvariable=self.password)
password_entry.pack()
confirm = Button(self.frame, text='Login', command = self.logincheck)
confirm.pack()
loginquit = Button(self.frame, text='Cancel', command=quit)
loginquit.pack()
def clearframe(self):
# Destroy all children of the class's frame.
for child in self.frame.winfo_children():
child.destroy()
root = Tk()
admin = Admin(root)
admin.login()
mainloop()
I am writing a Password code. I need a way to put to commands into one button so that it will destroy the window and get the username and password when I click the login button. I have looked through this site and non of the methods work for me so I need clarity on what I need to do to fix this.
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_1 = Label(self, text="Username")
self.label_2 = Label(self, text="Password")
self.entry_1 = Entry(self)
self.entry_2 = Entry(self, show="*")
self.label_1.grid(row=0, sticky=E)
self.label_2.grid(row=1, sticky=E)
self.entry_1.grid(row=0, column=1)
self.entry_2.grid(row=1, column=1)
self.checkbox = Checkbutton(self, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
***def destroy(self):
self.destroy()
self.logbtn = Button(self, text="Login", command = self._login_btn_clickked,)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clickked(self):
username = self.entry_1.get()
password = self.entry_2.get()
if username == "jake" and password == "hey":
tm.showinfo("Login info", "Welcome Jake")
master=Tk()
def login2():
tm.showinfo("Logging in", "Logging In...")
b = Button(master, text="Enter GUI", command=login2)
b.pack()
else:
tm.showerror("Login error", "Incorrect username")***
root = Tk()
lf = LoginFrame(root)
root.mainloop()
You should never call Tk() more than once in your program. If you need additional windows, use Toplevel().
However, in your case you don't need that either. You are on the right track of destroying the frame, now you just need to initiate a new frame. We can put that logic into a Tk class:
import tkinter as tk
class Mainframe(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.frame = FirstFrame(self)
self.frame.pack()
def change(self, frame):
self.frame.pack_forget() # delete currrent frame
self.frame = frame(self)
self.frame.pack() # make new frame
class FirstFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Enter password")
master.geometry("300x200")
self.status = tk.Label(self, fg='red')
self.status.pack()
lbl = tk.Label(self, text='Enter password')
lbl.pack()
self.pwd = tk.Entry(self, show="*")
self.pwd.pack()
self.pwd.focus()
self.pwd.bind('<Return>', self.check)
btn = tk.Button(self, text="Done", command=self.check)
btn.pack()
btn = tk.Button(self, text="Cancel", command=self.quit)
btn.pack()
def check(self, event=None):
if self.pwd.get() == 'password':
self.master.change(SecondFrame)
else:
self.status.config(text="wrong password")
class SecondFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Main application")
master.geometry("600x400")
lbl = tk.Label(self, text='You made it to the main application')
lbl.pack()
if __name__=="__main__":
app=Mainframe()
app.mainloop()
I'm new im Python, just started to learn about class and tkinter, so forgive me "messy" code.
I'm trying to enter some string to field nr1, and after click a button, print this string in console and store this value for later:
from tkinter import Tk, BOTH, RIGHT, RAISED, BOTTOM, TOP, X, StringVar
from tkinter.ttk import Frame, Button, Entry
class AD(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, v=None, raw_input=None)
self.parent = parent
self.parent.geometry("250x150+300+300")
self.parent.title("Trolollo")
self.parent.resizable(False, False)
self.inp = None
self.v = StringVar()
self.raw_input = None
self.initUI()
def user_input(self):
global inp
a = self.raw_input(self.v.get())
inp = a
return inp
def initUI(self):
self.pack(fill=BOTH, expand=True)
frame = Frame(self, relief=RAISED, borderwidth=0)
frame.pack(fill=BOTH, expand=True)
self.entry1 = Entry(frame, textvariable=self.v)
self.entry1.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.entry1.focus_set()
rename_button = Button(frame, text="Dispaly text", command = self.user_input())
rename_button.pack(side=TOP, expand=False, padx=2, pady=2)
entry2 = Entry(frame)
entry2.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
quit_button = Button(self, text="Quit", command=self.quit)
quit_button.pack(side=RIGHT, padx=5, pady=5)
ok_button = Button(self, text="OK")
ok_button.pack(side=RIGHT, padx=5, pady=5)
def main():
root = Tk()
app = AD(root)
root.mainloop()
if __name__ == '__main__':
main()
After executing code, i get:
TypeError: 'NoneType' object is not callable
Any help would me appreciated
ISSUES:
First issue laid in your rename_button's option "command=self.user_input()". You were suppose to name the function
and not execute the function. Putting the () symbol meant you
executed the function when your code loaded, i.e. it executed once
w/o pressing the rename button.
Second issue was the erroneous code in your function user_input. This caused your error msg.
ANSWER: Code with the suggested corrections.
from tkinter import *
from tkinter.ttk import *
class AD(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, v=None, raw_input=None)
self.parent = parent
self.parent.geometry("250x150+300+300")
self.parent.title("Trolollo")
self.parent.resizable(False, False)
self.inp = None
self.v = StringVar()
self.raw_input = None
self.initUI()
def user_input(self):
# Get entry1 value, store it as an attribute and print to console
self.raw_input = self.v.get()
print(self.raw_input)
def initUI(self):
self.frame = Frame(self, relief=RAISED, borderwidth=0)
self.frame.pack(fill=BOTH, expand=True)
self.entry1 = Entry(self.frame, textvariable=self.v)
self.entry1.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.entry1.focus_set()
#self.rename_button = Button(self.frame, text="Dispaly text",
# command = self.user_input())
self.rename_button = Button(self.frame, text="Display text",
command = self.user_input)
self.rename_button.pack(side=TOP, expand=False, padx=2, pady=2)
# You can remove the triple quotes to display these widgets
"""
self.entry2 = Entry(self.frame)
self.entry2.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.quit_button = Button(self.frame, text="Quit", command=self.quit)
self.quit_button.pack(side=RIGHT, padx=5, pady=5)
self.ok_button = Button(self.frame, text="OK")
self.ok_button.pack(side=RIGHT, padx=5, pady=5)
"""
self.pack(fill=BOTH, expand=True)
def main():
root = Tk()
app = AD(root)
root.mainloop()
Your GUI :
SUGGESTIONS:
Do remember to put self. in front of your widgets.
Do test one widget at a time to help you debug your code.
I've been playing around with my first Python Tkinter GUI.
Below you van find te script I've made. Must be honest, I've looked around on the internet to find out how to do it.
When I run my script now I get 2 seperate windows.
One window, lets call this "window A", with my text and input boxes and one empty window, lets call this "window B".
When I click on "Run" in "window A" my phyton script(tennisMatchProbability.py in this case) is triggered and the results of that script (tennisMatchProbability.py) are displayed in "window B".
This is the output that "tennisMatchProbability.py" gives.
Server Game = 0.735729230769
Receiver Game= 0.264270769231
Tiebreak = 0.337026817252
Server Set = 0.205146215901
Receiver Set= 0.794853784099
Match Server= 0.108987765053
Match Receiver= 0.891012234947
What I would like to achieve is that both windows are merged into one window.
I've been trying everything that I could think of but can't figure it out.
from Tkinter import *
import sys
sys.path.append("C:\Users\Magali\Desktop\Tennis\tennisMatchProbability.py")
class App(Frame):
def run_script(self):
sys.stdout = self
try:
del(sys.modules["tennisMatchProbability"])
except:
## Yeah, it's a real ugly solution...
pass
import tennisMatchProbability
tennisMatchProbability.matchProb()
sys.stdout = sys.__stdout__
def build_widgets(self):
self.text1 = Text(self)
self.text1.pack(side=TOP)
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
Label(master, text="Game Score").grid(row=2)
Label(master, text="Set Score").grid(row=3)
e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)
e4 = Entry(master)
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)
e4.delete(0,END)
e1.insert(10,"Novak")
e2.insert(10,"Djokovic")
e3.insert(10,"30-15")
e4.insert(10,"3-1")
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
Button(master, text='Run', command=self.run_script).grid(row=4, column=1, sticky=W, pady=4)
def write(self, txt):
self.text1.insert(INSERT, txt)
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.build_widgets()
root = Tk()
app = App(master = root)
app.mainloop()
The answer is easy:
In the build_widgets method you are constructing a new Tk frame and tcl interpreter with
master = Tk()
You should never have two Tk() calls in your application.
The solution is to delete this line and change every occurance of master to self. Self represent your app class, which inherits from the tk.Frame class and is therefore your main frame.
Also your construction of run_scipt is rather weird. Why don't you do it like this?
def run_script(self):
inputs = self.read_tk_fields()
result = tennisMatchProbability.matchProb(inputs)
Here is the full code
from Tkinter import *
import sys
sys.path.append("C:\Users\Magali\Desktop\Tennis\tennisMatchProbability.py")
import tennisMatchProbability
class App(Frame):
def run_script(self):
inputs = self.read_tk_field()
result = tennisMatchProbability.matchProb(inputs)
self.show_prob_result(result)
def show_prob_result(self,result):
self.result_label.config(text=result)
def build_widgets(self):
Label(self, text="First Name").grid(row=0)
Label(self, text="Last Name").grid(row=1)
Label(self, text="Game Score").grid(row=2)
Label(self, text="Set Score").grid(row=3)
e1 = Entry(self)
e2 = Entry(self)
e3 = Entry(self)
e4 = Entry(self)
self.result_label = Label(self)
e1.insert(10,"Novak")
e2.insert(10,"Djokovic")
e3.insert(10,"30-15")
e4.insert(10,"3-1")
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
self.result_label.grid(row=4, column=1)
Button(self, text='Run', command=self.run_script).grid(row=5, column=1, sticky=W, pady=4)
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.build_widgets()
root = Tk()
app = App(master = root)
app.mainloop()
#Jannick, with your script I don't get the results in the GUI. With your script I get the results in CMD and the "Run" bottun gives an error
With my code below I get the results in the GUI.
from Tkinter import *
import sys
sys.path.append("C:\Users\Magali\Desktop\Tennis\tennisMatchProbability.py")
class App(Frame):
def run_script(self):
sys.stdout = self
try:
del(sys.modules["tennisMatchProbability"])
except:
## Yeah, it's a real ugly solution...
pass
import tennisMatchProbability
tennisMatchProbability.matchProb()
sys.stdout = sys.__stdout__
def build_widgets(self):
self.text1 = Text(self)
self.text1.grid(row=5)
Label(self, text="First Name").grid(row=0)
Label(self, text="Last Name").grid(row=1)
Label(self, text="Game Score").grid(row=2)
Label(self, text="Set Score").grid(row=3)
e1 = Entry(self)
e2 = Entry(self)
e3 = Entry(self)
e4 = Entry(self)
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)
e4.delete(0,END)
e1.insert(10,"Novak")
e2.insert(10,"Djokovic")
e3.insert(10,"30-15")
e4.insert(10,"3-1")
e1.grid(row=0,column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
Button(self,text='Run', command=self.run_script).grid(row=4, column=1, sticky=W, pady=4)
def write(self, txt):
self.text1.insert(INSERT, txt)
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.build_widgets()
root = Tk()
app = App(master = root)
app.mainloop()
Whenever the function save() runs I get an error saying that the variable that holds the Text() function does not exist. I want the GUI to save whatever is inputted at the point when the Activate button is pressed.
from tkinter.ttk import *
class Example(Frame):
def __init__(self, parent= None):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("TL;DR")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(3, pad=7)
self.rowconfigure(3, weight=1)
self.rowconfigure(5, pad=7)
lbl = Label(self, text="Enter Text")
lbl.grid(sticky=W, pady=4, padx=5)
area = Text(self)
area.grid(row=1, column=0, columnspan=2, rowspan=4,
padx=5, sticky=E+W+S+N)
abtn = Button(self, text="Activate", command= self.save)
abtn.grid(row=1, column=3)
cbtn = Button(self, text="Close", command = self.client_exit)
cbtn.grid(row=2, column=3, pady=4)
hbtn = Button(self, text="Help", command= self.help1)
hbtn.grid(row=5, column=0, padx=5)
def save(self):
text = self.area.get("1.0",'end-1c')
with open("filepy.txt", "a") as outf:
outf.write(text)
def help1(self):
messagebox.showinfo('Help')
def client_exit(self):
exit()
def main():
root = Tk()
root.geometry("400x300+300+300")
app = Example(root)
if __name__ == '__main__':
main()
My question is: how do I save any text in the TextBox when the activate button is pressed?
In save() method, you are trying to access self.area but you did not created it.
area = Text(self) # class variable
self.area = Text(self)# instance variable
To be able to use self to access area you should change your code:
...
self.area = Text(self)
self.area.grid(row=1, column=0, columnspan=2, rowspan=4,
padx=5, sticky=E+W+S+N)
...