I am having trouble getting outputs from my python form - python

I am having trouble gaining the outputs from this form and i cant seem to identify where its going wrong.
from tkinter import *
def Button_to_text():
firstname_info = firstname.get()
lastname_info = lastname.get()
age_info = age.get()
print(firstname_info,lastname_info,age_info)
screen = Tk()
screen.geometry("500x500")
screen.title("python_form")
heading = Label(text = "Demo Form",bg = "orange", fg="black",width = "500")
heading.pack()
firstname_text = Label(text="firstname")
lastname_text = Label(text="lastname")
age_text = Label(text="age")
firstname_text.place(x=60, y= 40)
lastname_text.place(x=60,y=80)
age_text.place(x=60,y=120)
firstname = StringVar()
lastname = StringVar()
age = IntVar()
firstname_entry = Entry(textvariable = firstname)
lastname_entry = Entry(textvariable = lastname)
age_entry = Entry(textvariable = age)
firstname_entry.place(x=160, y=40)
lastname_entry.place(x=160,y=80)
age_entry.place(x=160,y=120)
register = Button(text = "register", width= "30",height ="2", command = Button_to_text())
register.place(x=50,y=290)
I followed a tutorial and my computing teacher cant help because he doesn't know python. plus my friends cant seem to identify the issue there are also no errors coming up so I know its a logic error and i also cant work out how to step so i can check variables
thanks to anyone who can help.

There are two problems with your code:
You have to use a mainloop to keep the window being displayed continuously.
You should not use the parentheses() while passing any function to a Button as an argument.
Note: And if the function has its own parameters then you will have to use lambda while passing it to a Button. But in your case, you can simply remove the parentheses().
Here's the fixed code:
from tkinter import *
def Button_to_text():
firstname_info = firstname.get()
lastname_info = lastname.get()
age_info = age.get()
print(firstname_info, lastname_info, age_info)
screen = Tk()
screen.geometry("500x500")
screen.title("python_form")
heading = Label(text="Demo Form", bg="orange", fg="black", width="500")
heading.pack()
firstname_text = Label(text="firstname")
lastname_text = Label(text="lastname")
age_text = Label(text="age")
firstname_text.place(x=60, y=40)
lastname_text.place(x=60, y=80)
age_text.place(x=60, y=120)
firstname = StringVar()
lastname = StringVar()
age = IntVar()
firstname_entry = Entry(textvariable=firstname)
lastname_entry = Entry(textvariable=lastname)
age_entry = Entry(textvariable=age)
firstname_entry.place(x=160, y=40)
lastname_entry.place(x=160, y=80)
age_entry.place(x=160, y=120)
register = Button(text="register", width="30", height="2", command=Button_to_text)
register.place(x=50, y=290)
screen.mainloop()
Note:
As a good practice, you should always use small letters in the names of functions like this: def button_to_text():.
And you should always import tkinter as tk instead of importing all * from tkinter. It is always a good practice. The only change you will need to do in the program is that you will need to use tk. before each item belonging to tkinter. Like this: screen = tk.Tk()

Related

I want to make a benchmark app in python using Tkinter

I want it to show the user input but it is not showing. Please send help.
I have tried code from multiple posts but no luck.
I was able to make it show the 'selected' option but for no avail. Please help me
import tkinter as tk
from tkinter.ttk import *
app = tk.Tk()
# Functions and scripts
def OnSubmit():
print(str(usrnme.get()))
print(str(passw.get()))
print(str(selected.get()))
app.title("Pymark: Landing Page")
app.geometry("600x600")
app.resizable(0, 0)
desc = """
PyMark is the first benchmark created using python's native GUI creator "Tkinter" and using hashes to rank performance.
The sofware is light and can run on older CPU's like i7-4510U (the processor I use) and does not require a lot of memory.
I am still open for constructive critisism and community feedback on my work as I am a beginner programmer.
IMPORTANT: PyMark can still experience bugs thus, pull requests are encouraged!
Please continue enjoying PyMark!
"""
# Landing Page
lpframe = Frame(app)
mainheading = Label(lpframe, text="Welcome to PyMark!", font = ('Times New Roman', 20))
maindesc = Label(lpframe, text=f'{desc}', font = ('Times New Roman', 9))
lpframe.pack()
mainheading.pack(padx = 10, pady = 10)
maindesc.pack(padx = 10, pady = 10)
# Login Page
loginframe = Frame(app)
headerframe = Frame(loginframe, relief = 'groove')
loginheader = Label(headerframe, text='Login / Register: ', font = ('Times New Roman', 12))
usrnmelb = Label(loginframe, text = 'Username: ', font = ('Times New Roman', 9))
passlb = Label(loginframe, text = 'Password: ', font = ('Times New Roman', 9))
selected = tk.StringVar()
register = Radiobutton(loginframe, text='Register', value='reg', variable=selected)
login = Radiobutton(loginframe, text='Login', value='log', variable=selected)
submitbtn = Button(loginframe, text = 'Submit', command=OnSubmit)
usrnmeentr = Entry(loginframe)
passentr = Entry(loginframe)
loginframe.pack()
headerframe.pack(padx = 20, pady = 20)
loginheader.pack(padx = 20, pady = 20)
usrnmelb.pack()
usrnmeentr.pack()
passlb.pack()
passentr.pack()
register.pack()
login.pack()
submitbtn.pack(padx = 10, pady = 10)
usrnme = tk.StringVar()
passw = tk.StringVar()
usrnmeentr.focus()
app.mainloop()
I expected it to return the username, password and the selected option but it only told the selected option and nothing else.
The OnSubmit() function does not get the correct inputs to print.
Get the entryfields content with the method .get().
In your case the OnSubmit() function should look like this:
def OnSubmit():
print(str(usrnmeentr.get())) #usrnme.get() was not the name of the entry box
print(str(passentr.get()))
print(str(selected.get()))
You must link your Entry to Stringvar(), not your radio buttons
import tkinter as tk
app = tk.Tk()
app.geometry('300x300')
# Functions and scripts
def OnSubmit():
print(var.get())
var = tk.StringVar()
entry = tk.Entry(app, textvariable=var)
entry.pack()
bt = tk.Button(app, text='Show', command=OnSubmit)
bt.pack()
app.mainloop()

(python) Disable the button in Tkinter when passwords do not match

How to disable the button in tkinter window when two passwords does not match?
My work:
from tkinter import *
from functools import partial
root = Tk()
root.geometry('280x100')
root.title('Tkinter Password')
def validation_pw(ep,cp):
if ep.get() == cp.get():
Label(root, text = "Confirmed").grid(column=0, row=5)
else:
Label(root, text = "Not matched").grid(column=0, row=5)
# check_button['state'] = DISABLED <============================
ep = StringVar()
cp = StringVar()
Label1 = Label(root, text = "Enter Password").grid(column=0, row=0)
pwEnty = Entry(root, textvariable = ep, show = '*').grid(column=1, row=0)
# Confirmed password label
Label2 = Label(root, text = "Confirm Password").grid(column=0, row=1)
pwconfEnty = Entry(root, textvariable = cp, show = '*').grid(column=1, row=1)
validation_pw = partial(validation_pw, ep,cp)
check_button = Button(root, text = "check", command = validation_pw).grid(column=0, row=4)
root.mainloop()
It shows if two passwords are not matched.
Now, I want to disable the check button if two passwords are not matched. I want the user cannot try the passwords anymore if failure.
So in the function validation_pw, I add check_button['state'] = DISABLED.
However, an error pops out
TypeError: 'NoneType' object does not support item assignment
How to fix this issue? Thanks!
Your checkbutton is actually None, because it's the result of the grid function.
To fix it, first declare the button, next grid it.
Before:
check_button = Button([...]).grid(column=0, row=4) # Result of Button.grid function
print(check_button) # None
After:
check_button = Button([...])
check_button.grid(column=0, row=4)
print(check_button) # Button object ...
You get the error of NoneType because at one point it was assigned nothing. This is because you used .grid on the same line as the button.
Fixed code:
check_button = Button(root, text = "check", command = validation_pw)
check_button.grid(column=0, row=4)

Python scroller for input

I wanted to start a new project with python, so i saw this so it looked cool so i wanted to give it a try, but i dont know how to make that scroller, all i found online was ways to make it scroll through text and documents, but not to control input, could someone help me make something like this?
and is there a way to make it display the number of characters above the scroller?
this is what i got online, i dont know if its the same thing as what i want
scrollbar1 = Scrollbar(master1, bg="green")
scrollbar1.pack( side = RIGHT, fill = Y )
You are looking for Scale widget . Please check this snippet and also please refer https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/scale.html for more details.
from tkinter import *
root = Tk()
root.geometry("100x100")
v1 = DoubleVar()
s1 = Scale( root, variable = v1,from_ = 1, to = 100,orient = HORIZONTAL)
l3 = Label(root, text = "Horizontal Scaler")
l1 = Label(root)
s1.pack(anchor = CENTER)
l3.pack()
l1.pack()
root.mainloop()
Edit
If you want the scale value dynamically on moving the pointer of scale and without triggering any button then please check this snippet along with screenshot.
from tkinter import *
def get_value(val):
scale_val = "Scale value= " + str(val)
label.config(text = scale_val)
root = Tk()
root.geometry("100x150")
v1 = DoubleVar()
s1 = Scale( root, variable = v1,from_ = 1, to = 100,orient = HORIZONTAL, command=get_value)
l3 = Label(root, text = "Horizontal Scaler")
l1 = Label(root)
s1.pack(anchor = CENTER)
l3.pack()
l1.pack()
label = Label(root)
label.pack()
root.mainloop()

no attribute to destroy

I have two functions the top_signup_click and the top_login_click. The top_signup_click function is below the top_login_click function. The top_login_click function doesn't work because the_top_signup_click function is below it. To fix that issue I'll have to put the top_signup_click above the top_login_click function, which does solve the issue but it also creates another issue, now the top_signup_click function doesn't work. For both functions to work they both have to be below each other, but I don't think that's possible. If you know any other ways to do this please help. I tried using global functions to fix it but it didn't work.
import tkinter as tk
import tkinter.font as font
import tkinter.messagebox
signup_button = None
root = tk.Tk()
root.geometry('360x460')
#login stuff
def login_click():
readfile = open("emails.txt", "r")
lines = readfile.readlines()
isIN = False
for line in lines:
if f'{entry.get()}, {entry1.get()}' in line:
isIN = True
if not isIN:
tk.messagebox.showinfo(message ="You got your email/password wrong, are you sure you signed in?")
else:
tk.messagebox.showinfo(message ="You hacker, the email/password is correct")
def signup_click():
file = open("emails.txt","a")
file.write (entry.get())
file.write(f', {entry1.get()}\n')
def top_login_click():
global signup_button
signup_button.destroy()
login_button = tk.Button(root, text="Login", bg='royalblue', fg='white', command = login_click, width = 15, height = 2)
login_button['font'] = button_font
login_button.place(x=88,y=330)
#when the top sign up button is pressed
def top_signup_click():
global login_button
login_button.destroy()
signup_button = tk.Button(root, text="Sign-Up", bg='royalblue', fg='white', command = login_click, width = 15, height = 2)
signup_button['font'] = button_font
signup_button.place(x=88,y=330)
top_font = font.Font(family='Helvetica', size=14, weight='bold')
label_font = font.Font(family='Helvetica', size=20)
button_font = font.Font(family='Helvetica', size=14, weight='bold')
top_login_button = tk.Button(root,text = 'Login',width = 15, height = 3, command = top_login_click)
top_login_button.place(x=0,y=0)
top_login_button['font'] = top_font
top_signup_button = tk.Button(root,text = 'Sign-Up',width = 15, height = 3, command = top_signup_click)
top_signup_button.place(x=180,y=0)
top_signup_button['font'] = top_font
username_label = tk.Label(root, text = 'Username: ' )
username_label['font'] =label_font
username_label.place(x=120,y=120)
entry = tk.Entry(root, width = 40)
entry.place(x=65,y=170, height = 30)
password_label = tk.Label(root, text = 'Password: ' )
password_label['font'] =label_font
password_label.place(x=120,y=230)
entry1 = tk.Entry(root, width = 40)
entry1.place(x=65,y=280, height = 30)
login_button = tk.Button(root, text="Login", bg='royalblue', fg='white', command = login_click, width = 15, height = 2)
login_button['font'] = button_font
login_button.place(x=88,y=330)
root.mainloop()
The top_login_click function is on line 29-34 and the top_signup_click function is on line 37-42. Thanks in advance.
I wanted to comment this but seems like I don't have enough reputation but here is what I think.
You have set the variable signup_button = None right below the import statements so signup_button is not really a tk.Button object, instead it's a NoneType variable.
So just remove that statement and create
signup_button = tk.Button(<args here>)
and You should be good.
and try using place_forget() instead of destroy() IFF destroy doesn't work for you.
Edit:
What I also think in your case that you may not really need to destroy the signup_up button because you haven't created one yet. Think about it this way (based on the GUI that comes up on running your code) - on the landing screen of your app (the first screen that comes up), you have a login form with two entry boxes for email & pword and a login button, along with two more buttons called top_login_button and top_signup_button. So You DO NOT have a signup_button as of now (and according to your code signup_button = None it's not a button). So if a user now clicks on the top_login_button, the statement signup_button.destroy() will look for widget with the name signup_button (which is set to None by you) so it raises the error.
You code will run fine in a case where user clicks on top_signup_button before clicking on top_login_button because in that case the signup_button will be actually set to be a tk.Button object.

'How to Create Hospital Management Systems in Python' from youtube - syntax error

I'm trying to use the How to Create Hospital Management Systems in Python - Full Tutorial as a programming exercise to learn how to define classes. I've followed along making no changes but I get an error (in the video the script runs fine). I'm using Python 3.7.4 (64bit) in Windows 10.
# Import packages
from tkinker import *
from tkinter import ttk
import random
import time;
import datetime
import tkinter.messagebox
# Define interface
class Hospital:
def__init__(self, root):
self.root = root
self.root.title("Hospital Management Systems")
self.root.geometry("1350x750+0+0")
self.root.configure(background='powder blue')
cmbNameTablets = StringVar()
Ref = StringVar()
Dose = StringVar()
NumberTablets = StringVar()
Lot = StringVar()
IssuedDate = StringVar()
ExpDate = StringVar()
DailyDose = StringVar()
PossibleSideEffects = StringVar()
FurtherInformation = StringVar()
StorageAdvice = StringVar()
DrivingUsingMachines = StringVar()
HowtoUseMedication = StringVar()
PatientID = StringVar()
PatientNHSNo = StringVar()
PatientName = StringVar()
DateOfBirth = StringVar()
PatientAddress = StringVar()
Prescription = StringVar()
MainFrame = Frame(self.root)
MainFrame.grid()
TitleFrame = Frame(MainFrame, bd = 20, width = 1350, padx = 20, relief = RIDGE)
TitleFrame.pack(side = TOP)
self.lblTitle = Label(TitleFrame, font = ('arial', 40, 'bold'), text = "Hospital Management Systems", padx = 2)
self.lblTitle.grid()
FrameDetail = Frame(MainFrame, bd = 20, width = 1350, height = 500, padx = 20, relief = RIDGE)
FrameDetail.pack(side = BOTTOM)
if__name__ == '__main__':
root = Tk()
application = Hospital(root)
root.mainloop()
Error message and traceback:
File "<ipython-input-7-e64c65d6c91e>", line 3
def__init__(self, root):
^
SyntaxError: invalid syntax
I expected it to look like it does at 10:36 in the video (a rather bare graphical interface).
I'm new to python and I've never defined classes before so I'm lost. Has the syntax changed since the video was made (August 2018), or is it because the instructor is using a different operating system/version of python?
Thanks for any help!
EDIT: error message and traceback added
1
Near the top of your source code:
from tkinker import *
You misspelled tkinter as tkinker with a k
2
Remove semi-colon from the line import time;
3
Put a space between def and __init__ in def__init__
4
Put a space between if and __name__ in if__name__

Categories

Resources