Changing the show of an entry box numerous times - python

I would like the contents of this my entry box to be uncovered from the * when the button is clicked, but then recovered when it is clicked again, and so on. Any ideas?
The code i have currently:
password_entry = Entry(root, width = 45, textvariable=user_password, show = "*")
def Show():
password_entry.config(show="")
show_password = Button(canvas, width = 31, height = 17, image = eye_img, bg = "gray33", relief = "flat", command = Show)
This only uncovers the password, and does not recover it when the button is reclicked.

Its seems that you are trying to make a toggle button. Edit your function. Get the value of current show. If it is * then change it to , if it is then change it to *. Your function can be:
def Show():
password_entry["show"] = "*" if password_entry["show"] == "" else ""
Here is a sample code that works like expected:
from tkinter import *
root = Tk()
password_entry = Entry(root, width = 45, show = "*")
password_entry.grid(row=0,column=0)
def Show():
password_entry["show"] = "*" if password_entry["show"] == "" else ""
show_password = Button(root,text="Show Password",bg = "gray33", relief = "flat", command = Show)
show_password.grid(row=0,column=1)
root.mainloop()

Related

Python program can't handle running exes

My program stops working after successfully running the two exes. here is the code:
from tkinter import *
import os
root = Tk()
root.geometry('350x150')
root.title("hurler")
photo = PhotoImage(file = "Logo_Image.png")
root.iconphoto(False, photo)
entry_text = Label(text = "Number of posts you wish to automate (between 1-12) * ")
entry_text.place(x = 15, y = 10)
num = StringVar()
time_entry = Entry(textvariable = num, width = "10")
time_entry.place(x = 15, y = 40)
def action():
global num
num = num.get()
if num == '1':
os.startfile('.\\hurl\\hurl.exe')
# exit()
if num == '2':
os.startfile('.\\hurl\\hurl.exe')
os.startfile('.\\hurl2\\hurl.exe')
# exit()
num = StringVar()
register = Button(root,text = "Make", width = "10", height = "2", command = action, bg = "lightblue")
register.place(x = 15, y = 70)
root.mainloop()
hurl takes in text entries and then runs a web driver exe after pressing the Post button. Heres a sample block from code from hurl:
from tkinter import *
import os
from time import sleep
root = Tk()
root.geometry('600x600')
root.title("hurl")
photo = PhotoImage(file = "Logo_Image.png")
root.iconphoto(False, photo)
def save_post():
emailE = email_in.get()
file1 = open ("user.txt", "w")
file1.write(emailE)
file1.close()
passE = pass_in.get()
file2 = open ('pass.txt', 'w')
file2.write(passE)
file2.close()
entry1_text = Label(text = "Email * ",)
entry2_text = Label(text = "Password * ",)
entry1_text.place(x = 15, y = 70)
entry2_text.place(x = 15, y = 130)
email_in = StringVar()
pass_in = StringVar()
email_entry = Entry(textvariable = email_in, width = "30")
pass_entry = Entry(textvariable = pass_in, width = "30")
def app():
os.system(".\Auto_Post_With_Photo.exe")
def everything():
save_post()
app()
register = Button(root,text = "Post", width = "10", height = "2", command = everything, bg = "lightblue")
register.place(x = 15, y = 380)
root.mainloop()
I'm hoping I don't need to show the last program to get an answer to the issue. The Issue I'm having is that the program runs perfectly until the button is pressed, and then the hurls exes crash.
But if I click on the two hurl.exe with my mouse and not this 3rd program pressing the post button won't crash.
Any ideas to fix this issue? Also, it's not due to the 'exit()s', it does the same thing with or without them. :)

How to delete an entry when I press a Button in Python Tkinter in a class

I am a beginner. Can I ask you some help?
How can I clear an entry in Python tkinter. I can't clear it.
I tried Parameters such as END and 'END' But I can't clear the entry when I Press a button
Can you answer as soon as possible thanks. I am working in a project now
This is my code:
from tkinter import *
class TkinScreen:
def main_screen_opening(self):
self.screen = Tk()
self.screen.geometry ('500x500')
self.screen.title ('Rwooggle Account')
my_heading1 = Label (text = 'Rwooggle.com', bg = 'blue', fg = 'yellow', font = ('Courier', 34, 'italic'), width = '500').pack()
my_heading = Label (text = 'Login', bg = 'blue', fg = 'black', font = ('Courier', 24, 'bold'), width = '500').pack()
def variables(self):
self.username_var = StringVar()
self.password_var = StringVar()
self.age_var = IntVar()
self.city_var = StringVar()
def labels_entries(self):
self.username_text = Label (text = 'Username*', font = ('Courier', 18)).pack()
self.username_entry = Entry (textvariable = self.username_var, width = '30').pack()
Label (text = "", width = '30').pack()
self.password_text = Label (text = 'Password*', font = ('Courier', 18)).pack()
self.password_entry = Entry (textvariable = self.password_var, width = '30').pack()
Label (text = "", width = '30').pack()
self.age_text = Label (text = 'Age', font = ('Courier', 18)).pack()
self.age_entry = Entry (textvariable = self.age_var, width = '30').pack()
Label (text = "", width = '30').pack()
self.city_text = Label (text = 'Country', font = ('Courier', 18)).pack()
self.city_entry = Entry (textvariable = self.city_var, width = '30').pack()
Label (text = "", width = '30').pack()
def button(self):
log_in_but = Button (text = 'Log In', font = ('Courier', 20), command = self.button_command).pack()
def button_command(self):
print ('User Sucessfully Logged In')
self.user_info = self.username_var.get()
self.pass_info = self.password_var.get()
self.pass_print = '*' * (len(self.pass_info))
self.age_info = self.age_var.get()
self.city_info = self.city_var.get().capitalize()
txt_info = f"""\
Username : {self.user_info}
Password : {self.pass_print}
Age : {self.age_info}
Country : {self.city_info}
"""
print (txt_info)
self.username_entry.delete(0, 'end')
self.password_entry.delete(0, 'end')
self.age_entry.delete(0, 'end')
self.city_entry.delete(0, 'end')
def function(self):
self.screen.mainloop()
tkint = TkinScreen ()
tkint.main_screen_opening()
tkint.variables()
tkint.labels_entries()
tkint.button()
tkint.function()
This is the error
User Sucessfully Logged In
Username : FFNNFD
Password : ******
Age : 12
Country : Eggreg
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Roger Geronimo\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\Roger Geronimo\Documents\Programming\SublimeText3\baf.py", line 53, in button_command
self.username_entry.delete(0, 'end')
AttributeError: 'NoneType' object has no attribute 'delete'
I also tried the END Parameter
Thank you in advance
Just change
self.username_entry = Entry (textvariable = self.username_var, width = '30').pack()
to
self.username_entry = Entry (textvariable = self.username_var, width = '30')
self.username_entry.pack()
I recommend to do this to all the entry boxes and then proceed as you normally do and it will solve the error :D
Explanation:
This is because self.username_entry = Entry (....).pack() returns None, ie, when you use self.username_entry.delete(0,'end') you are saying Entry (....).pack().delete(0,'end') which does not exist in the first place and since self.username_entry = Entry (....).pack() is None they give error, you received.
Extra tip:
I recommend using a master argument on your widgets, like, Entry(root) or when you work with more windows, itll cause havoc.
Instead of saying print ('User Sucessfully Logged In') you can use something like a messagebox with tkinter. Here is how
If you have any doubts, or errors, do let me know
Cheers
Whatever entry you want to clear , use entry.set('') in a function which will be called when button is clicked

Activate Entry Box from Listbox in Tkinter

I'm trying to create a GUI to collect three inputs from a user, where the first input has two options (based on a Listbox), like the image below (where the option "NACA" is selected):
The problem is with the Listbox. I guess the options are overlapping each other. For example, If I select the NACA option (image above), and then I select the .txt option, some part of the NACA label remains:
And of course, just the labels are appearing, not the entry_boxes to type inside (if I delete the part of the listBox, the entry_boxes of the last two input appers, so I really guess the problem is with the ListBox)
import tkinter as tk
root = tk.Tk()
root.geometry('400x300')
root.resizable(0, 0)
menu_inicial = tk.Canvas(root, width = 400, height = 300)
menu_inicial.pack()
def naca_box():
naca_entry_box = tk.Entry(menu_inicial)
menu_inicial.create_window(200, 30, window=naca_entry_box)
naca_label = tk.Label(root, text="Enter NACA:")
naca_label.pack()
naca_label.place(x=50, y = 50)
def txt_box():
txt_entry_box = tk.Entry(menu_inicial)
menu_inicial.create_window(200, 30, window=txt_entry_box)
txt_label = tk.Label(root, text="Enter .txt:")
txt_label.pack()
txt_label.place(x=50, y = 50)
def aoa_box():
aoa_entry_box = tk.Entry(root)
menu_inicial.create_window(200, 60, window=aoa_entry_box)
aoa_label = tk.Label(root, text="Enter AoA (º):")
aoa_label.pack()
aoa_label.place(x=50, y = 80)
def panel_box():
panel_entry_box = tk.Entry(root)
menu_inicial.create_window(200, 90, window=panel_entry_box)
panel_label = tk.Label(root, text="Enter Nº Panels:")
panel_label.pack()
panel_label.place(x=40, y = 110)
def update_box(*args):
selection = box_list.curselection()
lb_value.set(options[selection[0]] )
if selection[0] == 0:
naca_box()
else:
txt_box()
options = ['NACA', '.txt']
listCon = tk.StringVar(value=options)
box_list = tk.Listbox(menu_inicial, listvariable=listCon, width=10, height=2, selectmode=tk.SINGLE)
box_list.grid(row=0, column=0)
box_list.bind('<<ListboxSelect>>', update_box)
lb_value=tk.StringVar()
aoa_box()
panel_box()
root.mainloop()
How can I proceed with this? Is a problem with the "IF" statement to choose the options ? (I don't know if this is the best what to do this...)
The problem is that while you clicking button each time,
you are creating label each time,
if you want to change the text in the label you created,use 'config()'
change your code like this,
sample_label=tk.Label(root)
sample_label.place(x=50, y = 50)
def naca_box():
naca_entry_box = tk.Entry(menu_inicial)
menu_inicial.create_window(200, 30, window=naca_entry_box)
sample_label.config(text="Enter NACA:")
def txt_box():
txt_entry_box = tk.Entry(menu_inicial)
menu_inicial.create_window(200, 30, window=txt_entry_box)
sample_label.config(text="Enter .txt:")

Random tkinter window opening on if/else statement

I'm wondering if I got my if else statement wrong or if its a tkinter issue. I want it so that if a 0 is left in any or all boxes, it gives an error message. But after the error message is closed, it opens a random blank window. This is my code. The specific area is the if else statement within the function valueget()
import tkinter as tk
def mainwindow():
mainwindow = tk.Tk()
mainwindow.title('Enter values')
mainwindow.geometry('160x110')
mainwindow.config(bg='#aaf0d1')
tk.Label(mainwindow, text = 'Enter a', font = ('verdana'), bg='#aaf0d1').grid(row=0)
tk.Label(mainwindow, text = 'Enter b', font = ('verdana'), bg='#aaf0d1').grid(row=1)
tk.Label(mainwindow, text = 'Enter c', font = ('verdana'), bg='#aaf0d1').grid(row=2)
getA = tk.IntVar()
aBox = tk.Entry(mainwindow, textvariable = getA, width=3, bg='#aaf0d1')
aBox.grid(row=0, column=1)
aBox.config(highlightbackground='#aaf0d1')
getB = tk.IntVar()
bBox = tk.Entry(mainwindow, textvariable = getB, width=3, bg='#aaf0d1')
bBox.grid(row=1, column=1)
bBox.config(highlightbackground='#aaf0d1')
getC = tk.IntVar()
cBox = tk.Entry(mainwindow, textvariable = getC, width=3, bg='#aaf0d1')
cBox.grid(row=2, column=1)
cBox.config(highlightbackground='#aaf0d1')
button = tk.Button(mainwindow, text='Obtain roots', command = lambda: valueget(), font = ('verdana'), highlightbackground='#aaf0d1')
button.grid(row=4)
button.config(bg='#aaf0d1')
def valueget():
readA = getA.get()
readB = getB.get()
readC = getC.get()
intA = int(readA)
intB = int(readB)
intC = int(readC)
negroot = (readB**2)-(4*readA*readC)
quadformulaplus = (-readB + (pow(negroot,0.5)))/(2*readA) #quad forumla
quadformulaminus = (-readB - (pow(negroot,0.5)))/(2*readA) #quad forumla
messagewindow = tk.Tk()
messagewindow.geometry('290x50')
messagewindow.title('Roots of the equation')
messagewindow.config(bg='#aaf0d1')
if readA == 0 or readB==0 or readC==0 or (readA==0 and readB==0 and readC==0):
errorwindow = tk.messagebox.showerror(message='none').pack()
else:
label = tk.Label(messagewindow, text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}', bg='#aaf0d1', font = ('verdana'))
label.grid(row=1)
closebutton = tk.Button(messagewindow, text='Close', command = lambda: messagewindow.destroy(), font = ('verdana'), highlightbackground='#aaf0d1')
closebutton.grid(row=2)
closebutton.config(bg='#aaf0d1')
messagewindow.mainloop()
# print(f'the roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}')
mainwindow.mainloop()
def startup():
startpage = tk.Tk()
startpage.title('Solver')
photo = tk.PhotoImage(file = r"/Users/isa/Desktop/DiffEqns/cover.png") #image load
coverbutton = tk.Button(startpage, image = photo, command = lambda: [startpage.destroy(), mainwindow()])
coverbutton.pack()
coverbutton.configure(highlightbackground='#aaf0d1')
startpage.mainloop()
startup()
Here's a basic idea of what I would do:
import tkinter as tk
from tkinter import messagebox
def mainwindow(root):
# Creates a toplevel window
mainwindow = tk.Toplevel()
mainwindow.protocol("WM_DELETE_WINDOW", root.destroy) # This overrides the "X" being clicked to also destroy the root window.
root.withdraw() # "Hides" the root window, leaving it (and mainloop) running in the background.
mainwindow.title('Enter values')
mainwindow.geometry('160x110')
mainwindow.config(bg='#aaf0d1')
# Since all three of the labels/entries are the same
# we can save space by generating them in a loop
entry_items = ('Enter a', 'Enter b', 'Enter c')
values = []
for x, item in enumerate(entry_items): # Using enumerate and x to assign rows
tk.Label(mainwindow, text = item,
font = ('verdana'), bg='#aaf0d1').grid(row=x) # Row assigned to x.
values.append(tk.StringVar()) # Appended StringVar to list.
tk.Entry(mainwindow,
textvariable = values[-1], # Uses the last value appended to the values list.
highlightbackground='#aaf0d1',
width=3,
bg='#aaf0d1').grid(row=x, column=1) # Row assigned to x.
tk.Button(mainwindow,
text='Obtain roots',
command = lambda vals = values: valueget(vals), # Here the button command is assigned with the values list
font = ('verdana'), bg='#aaf0d1',
highlightbackground='#aaf0d1').grid(row=3) # we know there are 3 items before this.
mainwindow.lift() # This is a method of bringing a window to the front
def valueget(vals):
# This line gets the values from the StringVars, converts them to ints,
# and returns them to their respective variables.
try:
readA, readB, readC = [int(val.get()) for val in vals]
except ValueError:
messagebox.showerror(title="Number Error", message='Values must be numbers')
return
# Here the variables are checked to see if they are 0
# Since each one is being checked if it is 0, there is no need to check if they are all 0.
for val in (readA, readB, readC):
if val == 0:
# If they are 0, shows an error message
messagebox.showerror(title="Zero Error", message='Values must not be zero')
return
# Creates a toplevel to display the results
messagewindow = tk.Toplevel()
messagewindow.title('Roots of the equation')
messagewindow.config(bg='#aaf0d1')
negroot = (readB**2)-(4*readA*readC)
quadformulaplus = (-readB + (pow(negroot,0.5)))/(2*readA) #quad forumla
quadformulaminus = (-readB - (pow(negroot,0.5)))/(2*readA) #quad forumla
tk.Label(messagewindow,
text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}',
bg='#aaf0d1',
font = ('verdana')).pack(padx = 5, pady = 2)
tk.Button(messagewindow,
text='Close',
command = messagewindow.destroy, # There is no need for a lambda for this.
font = ('verdana'),
bg = '#aaf0d1',
highlightbackground='#aaf0d1').pack(padx = 5, pady = 2)
# print(f'the roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}')
messagewindow.lift() # This is a method of bringing a window to the front
def startup():
startpage = tk.Tk()
startpage.title('Solver')
# COMMENTED OUT FOR TESTING
#photo = tk.PhotoImage(file = r"/Users/isa/Desktop/DiffEqns/cover.png") #image load
coverbutton = tk.Button(startpage,
# COMMENTED OUT FOR TESTING
#image = photo,
text = "TESTING", # HERE FOR TESTING
highlightbackground='#aaf0d1',
command = lambda root = startpage: mainwindow(root)).pack() # Passes the startpage to the mainwindow function.
startpage.mainloop() # The only mainloop you need.
startup()
I would recommend to improve the readability of the if-else statement for a start.
coefficients = [readA, readB, readC]
if sum(coefficients): # If they all are all zeros this will be False
if min(coefficients): # If any one is zero, this will be False
label = tk.Label(messagewindow, text = f'The roots are {quadformulaplus:.1f} and {quadformulaminus:.1f}', bg='#aaf0d1', font = ('verdana'))
label.grid(row=1)
closebutton = tk.Button(messagewindow, text='Close', command = lambda: messagewindow.destroy(), font = ('verdana'), highlightbackground='#aaf0d1')
closebutton.grid(row=2)
closebutton.config(bg='#aaf0d1')
else:
errorwindow = tk.messagebox.showerror(message='none').pack()
else:
errorwindow = tk.messagebox.showerror(message='none').pack()

Python Spin Boxes are copying each other and I don't see why?

I am writing a code to create a time calendar, and for some reason the starting and ending time dials are mirroring each other. I have looked over everything, but I can't see any reason why the code would do such a thing.
Here is the code?
from Tkinter import *
import math
Master = Tk()
def Value_Check():
Start_Hours = eval(Starting_Hours.get())
Start_Min = eval(Starting_Minutes.get())
End_Hours = eval(Ending_Hours.get())
End_Min = eval(Ending_Minutes.get())
Start_Time_Window = ((Start_Hours*60)+ Start_Min)
End_Time_Window = ((End_Hours*60)+ End_Min)
Total_Window = (Start_Time_Window - End_Time_Window)
Window_Hours = math.floor(Total_Window/60)
Window_Minutes = (Total_Window - Window_Hours)
print "You have a ", Window_Hours, "Hours and", Window_Minutes, "minute window to test"
Frame_Start_Window= Frame(Master)
Frame_Start_Window.pack()
#Setting the starting time of the testing window
Start_Time_Frame = Frame(Master)
Start_Time_Frame.pack( side = BOTTOM )
Starting_Title = Label(Frame_Start_Window, text = "When can you start testing? ")
Starting_Title.pack()
Starting_Hours = Spinbox(Frame_Start_Window, text = "Hour", from_ = 1, to = 24, wrap =True, width = 2, command = Value_Check)
Starting_Hours.pack(side = LEFT)
Collen_Title = Label(Frame_Start_Window, text = ":")
Collen_Title.pack(side = LEFT)
Starting_Minutes = Spinbox(Frame_Start_Window, text = "Minutes", from_ = 0, to = 59, wrap =True, width = 2, command = Value_Check)
Starting_Minutes.pack(side = LEFT)
#The end half of the testing window:
Frame_End_Window= Frame(Master)
Frame_End_Window.pack()
#Setting the starting time of the testing window:
End_Title = Label(Frame_End_Window, text = "What time do you HAVE to stop testing?")
End_Title.pack()
Ending_Hours = Spinbox(Frame_End_Window, text = "Hour", from_ = 1, to = 24, wrap =True, width = 2, command = Value_Check)
Ending_Hours.pack(side = LEFT)
Collen2_Title = Label(Frame_End_Window, text = ":")
Collen2_Title.pack(side = LEFT)
Ending_Minutes = Spinbox(Frame_End_Window, text = "Minutes", from_ = 0, to = 59, wrap =True, width = 2, command = Value_Check)
Ending_Minutes.pack(side = LEFT)
#Where the answer from the Test_Calculator button is displayed:
Results_Screen = Text(Master, height=2, width=65)
Results_Screen.pack()
Data_Reset = Button (Master, text = "Reset Values", command = Value_Check)
Data_Reset.pack()
mainloop()
The answer is that Spinbox has no text configuration parameter: It has textvariable, for which it's accepting text as an abbreviation. This means you have two independent Spinbox widgets both using the textvariable of Hour and two independent Spinbox widgets both using the textvariable of Minute. The textvariable setting tells the Spinbox to link the content of the Spinbox to the content of the named variable; any time the Spinbox changes, the named variable will change, and any time the named variable changes, the Spinbox will change. Thus, you change the value in one Spinbox, it updates the variable, which in turn updates the other Spinbox.

Categories