Function doesn't shows password in real time - python

When I click show password it shows password but when I input 1 more letter in the entry box then that letter doesn't show up but when I input one more letter the previous letter shows up but the letter which I inputed just now doesn't show up So I want the code to update the password in the Show password label(show) in real time.
Code:
from tkinter import *
win = Tk()
no=2
def evod():
global no
no+=1
def showpwd(e):
global no, t
def bind():
text1=t.get()
btn2=Button(win, text="hide",command=hide)
btn2.grid(row=0,column=1)
show.config(text=text1)
evod()
def hide():
show.config(text="")
btn3=Button(win, text="show",command=bind)
btn3.grid(row=0,column=1)
evod()
if no % 2==0:
txt=t.get()
btn2=Button(win, text="hide",command=hide)
btn2.grid(row=0,column=1)
show.config(text=txt)
else:
show.config(text="")
btn=Button(win, text="show",command=bind)
btn.grid(row = 0, column = 1)
def bind():
show.config(text=t.get())
ent.bind("<Key>", showpwd)
t = StringVar()
ent = Entry(win,show="*", textvariable=t)
ent.grid(row = 0, column = 0)
btn=Button(win, text="show",command=bind)
btn.grid(row = 0, column = 1)
show= Label(win,text="")
show.grid(row = 1, column = 0,sticky="w")
win.mainloop()

Related

Tkinter field in blank for Python

I need your help to figure out how to make the following coding:
My idea is to get a message if fields name and quantity are in blank at the time I execute a function through a button. I printed what is the value if name and quantity are in blank and program says it is .!entry and .!entry2 respectively.
Unfortunately it doesn't work. What I am doing wrong?
if name == .!entry and quantity == .!entry2:
message = Label(root, text = 'Name and Quantity required' , fg = 'red')
message.grid(row = 4, column = 0, columnspan = 2, sticky = W + E)
return
As #JordyvanDongen pointed out in the comments you should use entry.get() to get the text inside the the entry object.
I suggest this for you code, assuming the entry objects are named name and quantity:
if not name.get() or not quantity.get():
message = Label(root, text = 'Both name and quantity are required', fg = 'red')
message.grid(row = 4, column = 0, columnspan = 2, sticky = W + E)
return None
I changed the conditional to or so that if either of the fields are blank it will be triggered but you may want to change it back to and depending on your purposes..

UnboundLocalError: local variable 'qn' referenced before assignment

I'm getting the error "UnboundLocalError: local variable 'qn' referenced before assignment" on running the code. Why is that? How can I correct it? I'm new to tkinter so please try to keep it simple. This is part of the code for a game I was writing. It would be a great help if I could get an answer soon
from tkinter import *
from tkinter import messagebox
from io import StringIO
root = Tk()
root.title("Captain!")
root.geometry("660x560")
qn = '''1$who are you?$char1$i am joe$3$i am ben$2
2$what are you?$char2$i am a person$1$i am nobody$3
3$how are you?$char3$i am fine$2$i'm alright$1'''
var = '''1$10$-35$20$15$-20
2$9$7$30$-5$-15
3$10$-25$-15$10$5'''
class Game :
def __init__(self):
self.m_cur = {1:["Military",50]}
self.c_cur = {1:["People's",50]}
self.r_cur = {1:["Research",50]}
self.i_cur = {1:["Industrial",50]}
self.p_cur = {1:["Research",50]}
#function to clear all widgets on screen when called
def clear(self):
for widget in root.winfo_children():
widget.destroy()
#function to quit the window
def exit(self):
msg = messagebox.askquestion("Thank you for playing","Are you sure you want to exit?")
if msg == "yes" :
root.destroy()
else:
Game.main(self)
#start function
def start(self):
Label(root,text="Hello, what should we call you?",font=("segoe print",20)).grid(row=0,column=0)
name = Entry(root,width=20)
name.grid(row=1,column=0)
Button(root,text="Enter",font=("segoe print",20),command=lambda: Game.main(self)).grid(row=1,column=1)
self.name=name.get()
#main function
def main(self):
Game.clear(self)
Label(root,text="Welcome to the game",font=("segoe print",20)).grid(row=0,column=0)
Label(root,text='What do you want to do?',font=("segoe print",20)).grid(row=1,column=0)
Button(root,text="Start Game",font=("segoe print",20),command=lambda: Game.qn_func(self,1)).grid(row=2,column=0)
Button(root,text="Exit Game",font=("segoe print",20),command=lambda: Game.exit(self)).grid(row=3,column=0)
#function to check variables and display game over
def game_over(self,x_cur):
if x_cur[1][1]<=0 or x_cur[1][1]>=100 : #condition to check game over
Game.clear(self)
Label(root,text=x_cur)
Label(root,text="GAME OVER",font=("ariel",20)).place(relx=0.5,rely=0.5,anchor=CENTER)
Button(root,text="Continue",font=("segoe print",20),command=lambda: Game.main(self)).place(relx=0.5,rely=0.6)
#function to display question and variables
def qn_func(self,qn_num) :
Game.clear(self)
#accessing the questions
q_file = StringIO(qn)
#reading the question, options, next qn numbers and the character name from the file
qn_list = q_file.readlines()
qn = qn_list[qn_num-1].strip().split("$")[1]
char_name = qn_list[qn_num-1].strip().split("$")[2]
qn1 = qn_list[qn_num-1].strip().split("$")[3]
qn2 = qn_list[qn_num-1].strip().split("$")[5]
n_qn1 = int(qn_list[qn_num-1].strip().split("$")[4])
n_qn2 = int(qn_list[qn_num-1].strip().split("$")[6])
#displaying the character name and the question as a label frame widget with character name as parent
label_frame = LabelFrame(root,text = char_name,font = ("segoe print",20))
label = Label(label_frame,text = qn,font = ("segoe print",20))
label_frame.place(relx=0.5,rely=0.5,anchor=CENTER)
label.pack()
q_file.close()
#accessing variables
v_file = StringIO(var)
#reading values of variables from file
v_list = v_file.readlines()
self.r_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[1])
self.c_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[2])
self.i_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[3])
self.m_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[4])
self.p_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[5])
#running each variable through game_over to see if you are dead
Game.game_over(self,self.r_cur)
Game.game_over(self,self.c_cur)
Game.game_over(self,self.i_cur)
Game.game_over(self,self.m_cur)
Game.game_over(self,self.p_cur)
#defining the Doublevar variables
s_var1 = DoubleVar()
s_var2 = DoubleVar()
s_var3 = DoubleVar()
s_var4 = DoubleVar()
s_var5 = DoubleVar()
#setting the values in the scales
s_var1.set(self.r_cur[1][1])
s_var2.set(self.c_cur[1][1])
s_var3.set(self.i_cur[1][1])
s_var4.set(self.m_cur[1][1])
s_var5.set(self.p_cur[1][1])
#variables as scale widgets
scale1 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var1)
scale2 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var2)
scale3 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var3)
scale4 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var4)
scale5 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var5)
#displaying the scale widgets on the screen
scale1.grid(row=0,column=0)
scale2.grid(row=0,column=1)
scale3.grid(row=0,column=2)
scale4.grid(row=0,column=3)
scale5.grid(row=0,column=4)
#disabling the scales
scale1.config(state=DISABLED)
scale2.config(state=DISABLED)
scale3.config(state=DISABLED)
scale4.config(state=DISABLED)
scale5.config(state=DISABLED)
v_file.close()
#displaying the buttons on the screen
Button(root,text=qn1,command=lambda: Game.qn_func(self,n_qn1)).place(relx=0.2,rely=0.7,anchor=W,width=200,height=50)
Button(root,text=qn2,command=lambda: Game.qn_func(self,n_qn2)).place(relx=0.8,rely=0.7,anchor=E,width=200,height=50)
game = Game()
game.start()
root.mainloop()
You can see in this particular section that you have called on 'qn' before it was even defined:
#function to display question and variables
def qn_func(self,qn_num) :
Game.clear(self)
#accessing the questions
q_file = StringIO(qn)
#reading the question, options, next qn numbers and the character name from the file
qn_list = q_file.readlines()
qn = qn_list[qn_num-1].strip().split("$")[1]
The variable needs to be assigned a value before being used. Here, you call q_file = StringIO(qn) before you have defined qn = qn_list....

Python GUI EntryButtons

I'm making a small GUI application that deals with grades and whatnot and outputs the highest grades and etc.
Here's a part of the code:
root = Tk()
gradeList = []
def addGradeObject(name, percentage):
gradeList.append(Grade(name, percentage))
updateOutput()
print(gradeList)
def undoAdd():
try:
gradeList.pop(len(gradeList) - 1)
updateOutput()
print(gradeList)
except Exception:
pass
def updateOutput():
highestGrade.setText(highest_grade(gradeList))
lowestGrade.setText(lowest_grade(gradeList))
numFailed.setText(num_failed(gradeList))
addButton = Button(text = "Add Grade", command = lambda: addGradeObject (entryA.get(), entryB.get())).grid(row = 1, column = 4)
undoButton = Button(text = "Undo", command = undoAdd).grid(row = 2, column = 4)
entryA = Entry()
entryA.grid(row = 1, column = 1)
entryB = Entry()
entryB.grid(row = 1, column = 2)
highestGrade = Entry()
highestGrade.grid(row = 2, column = 1)
lowestGrade = Entry()
lowestGrade.grid(row = 3, column = 1)
numFailed = Entry()
numFailed.grid(row = 4, column = 1)
root.title("Grade Checker")
root.mainloop()
The problem is I'm getting this error:
AttributeError: 'Entry' object has no attribute 'setText'
I don't understand. When you create an Entry box, doesn't the object of class "Entry" have an attribute/method that allows you to set text to it? I really don't know why it's not working
Entry methods can be found here. As far as I can tell, there is no setText method. There is however an insert method that you could use to set the text (though you might wand to delete the current text first).
def set_text(entry, text):
entry.delete(0, tkinter.END)
entry.insert(0 text)
Alternatively, you can hook the entry up to a StringVar and use it's .set() and .get() methods. e.g. (from the linked docs above):
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()

Python sqlite3, tkinter display multible rows

I am new to python and recently i make dictionary using Python and Sqlite3 with tkinter.
When I run the code it returns multiple line in IDLE but in the GUI its only display the last result. I would like to display all the information in the GUI. Thanks you for any help and suggestion.
import tkinter
import sqlite3
class Dictionary:
def __init__(self,master =None):
self.main_window = tkinter.Tk()
self.main_window.title("Lai Mirang Dictionary")
self.main_window.minsize( 600,400)
self.main_window.configure(background = 'paleturquoise')
self.frame1 = tkinter.Frame()
self.frame2= tkinter.Frame(bg = 'red')
self.frame3 =tkinter.Text( foreground = 'green')
self.frame4 = tkinter.Text()
self.lai_label = tkinter.Label(self.frame1,anchor ='nw',font = 'Times:12', text = 'Lai',width =25,borderwidth ='3',fg='blue')
self.mirang_label = tkinter.Label(self.frame1,anchor ='ne',font = 'Times:12', text = 'Mirang',borderwidth ='3',fg ='blue')
self.lai_label.pack(side='left')
self.mirang_label.pack(side = 'left')
self.kawl_buttom= tkinter.Button(self.frame2 ,fg = 'red',font = 'Times:12',text ='Kawl',command=self.dic,borderwidth ='3',)
self.lai_entry = tkinter.Entry(self.frame2, width= 28, borderwidth ='3',)
self.lai_entry.focus_force()
self.lai_entry.bind('<Return>', self.dic,)
self.lai_entry.configure(background = 'khaki')
self.lai_entry.pack(side='left')
self.kawl_buttom.pack(side = 'left')
self.value = tkinter.StringVar()
self.mirang_label= tkinter.Label(self.frame3,font = 'Times:12',fg = 'blue',textvariable = self.value,justify = 'left',wraplength ='260',width = 30, height = 15,anchor = 'nw')
self.mirang_label.pack()
self.mirang_label.configure(background = 'seashell')
self.copyright_label = tkinter.Label(self.frame4,anchor ='nw',font = 'Times:12:bold',text = "copyright # cchristoe#gmail.com",width = 30,borderwidth = 3, fg = 'purple',)
self.copyright_label.pack()
self.frame1.pack()
self.frame2.pack()
self.frame3.pack()
self.frame4.pack()
tkinter.mainloop()
self.main_window.quit()
def dic(self, event = None):
conn = sqlite3.connect('C:/users/christoe/documents/sqlite/laimirangdictionary.sqlite')
c = conn.cursor()
kawl = self.lai_entry.get()
kawl = kawl + '%'
c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,))
c.fetchall
for member in c:
out = (member)
self.value.set(out)
print(out, )
dic=Dictionary()
You need to change:
c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,))
c.fetchall
for member in c:
out = (member)
self.value.set(out)
print(out, )
To:
for member in c.execute("SELECT * FROM laimirang WHERE lai LIKE ?", (kawl,)):
current_text = self.value.get()
new_text = current_text +( "\n" if current_text else "") +" ".join(member)
self.value.set(new_text)
The new version gets the current value of the StringVar value and then appends the results returned with a space inbetween for each row returned with each row on its own line. What you were doing however involved just updating the StringVar to be the current member object, and therefore it only ever had the last values.
This is how it looks with more than one line:

How can I put frames inside frames using tkinter?

I'm making a baseball program based on the strategy games produced by Avalon Hills from the 70s & 80s, and the last part is a gui. I've made all the code to run the game command line, and I've got the code to select lineups with a gui. I envision a 3by1 grid with a scoreboard on the first row, a text box displaying the result, out, home run, double play, etc., and the last row is divided between the pitcher and batter cards on the left side, and a frame of buttons. The frame will flip between an offence and defence frame. So first the defence frame comes up with options like pitching change, change position, and play ball. Play ball changes the frame to the offence options, which will be pinch hit, pinch run, steal, and so on. But how can I put the buttons inside a frame, then combine the player cards and buttons in another frame, and then add that to the main frame?
The DFrame & OFrame classes are inner classes (hence the "elf", not "self"). I've got the dynamic switching between the 2 Frames. My problem is breaking the DFrame main loop, it only plays the top of the first, and the self.roadOuts never increments. Here's what I've got:
while self.innings < 8.5 or self.homeScore == self.roadScore:
self.roadOuts = 0
while self.roadOuts < 3:
self.dFrame.mainloop()
class DFrame(Frame):
def __init__(elf, parent):
Frame.__init__(elf)
elf._playButton = Button(elf, text = 'Play Ball',
command = parent.oMenu)
elf._playButton.grid(row = 0, column = 0)
elf._pitchingButton = Button(elf, text = 'Pitching Change',
command = parent.pitchingChange)
elf._pitchingButton.grid(row = 1, column = 0)
elf._positionButton = Button(elf, text = 'Defensive Substitution',
command = parent.positionChange)
elf._positionButton.grid(row = 0, column = 1)
elf._alignButton = Button(elf, text = 'Change Positions',
command = parent.positionSwap)
elf._alignButton.grid(row = 1, column = 1)
elf._doubleButton = Button(elf, text = 'Double Switch',
command = parent.doubleSwitch)
elf._doubleButton.grid(row = 2, column = 0)
elf._walkButton = Button(elf, text = 'Intentional Walk',
command = parent.intentionalWalk)
elf._walkButton.grid(row = 2, column = 1)
elf._depthButton = Button(elf, text = 'Change Infield Depth',
command = parent.infieldDepth)
elf._depthButton.grid(row = 3, column = 0)
class OFrame(Frame):
def __init__(elf, parent):
Frame.__init__(elf)
elf._playButton = Button(elf, text = 'Play Ball',
command = parent.atBat)
elf._playButton.grid(row = 0, column = 0)
elf._pinchHitButton = Button(elf, text = 'Pinch Hit',
command = parent.pinchHit)
elf._pinchHitButton.grid(row = 1, column = 0)
elf._prfButton = Button(elf, text = 'Pinch Run First',
command = parent.pinchRunFirst)
elf._prfButton.grid(row = 0, column = 1)
elf._prsButton = Button(elf, text = 'Pinch Run Second',
command = parent.pinchRunSecond)
elf._prsButton.grid(row = 1, column = 1)
elf._prtButton = Button(elf, text = 'Pinch Run Third',
command = parent.pinchRunThird)
elf._prtButton.grid(row = 2, column = 1)
elf._stealButton = Button(elf, text = 'Steal',
command = parent.steal)
elf._stealButton.grid(row = 2, column = 0)
elf._bunt4HitButton = Button(elf, text = 'Bunt for a hit',
command = parent.bunt4AHit)
elf._bunt4HitButton.grid(row = 3, column = 0)
elf._hitNRunButton = Button(elf, text = 'Hit And Run',
command = parent.hitAndRun)
elf._hitNRunButton.grid(row = 4, column = 0)
elf._sacButton = Button(elf, text = 'Sacrifice',
command = parent.sacrifice)
elf._sacButton.grid(row = 4, column = 1)
elf._squeezeButton = Button(elf, text = 'Squeeze',
command = parent.squeeze)
elf._squeezeButton.grid(row = 3, column = 1)
the next method is called when the DFrame "play ball" button is clicked, and it makes the OFrame.
def oMenu(self):
self.dFrame.grid_forget()
self.dFrame.destroy()
self.oFrame = self.OFrame(self)
self.oFrame.grid(row = 1, column = 1)
self.oFrame.mainloop()
and at the end of an at bat, I have:
self.oFrame.grid_forget()
self.oFrame.destroy()
self.dFrame = self.DFrame(self)
self.dFrame.grid(row = 1, column = 1)
I'm not sure I understand your question. It seems like you know how to put one frame in another (It is really not much different than adding a Button to a frame -- or any other widget). I think what you're asking is how to dynamically switch which frame is being displayed at any given time.
You probably want the grid_forget method. using the play_ball button should cause the defense_frame to call it's grid_forget method, while re-gridding the the offense_frame. Of course, this would be pack_forget if you're using the pack geometry manager.
EDIT
Added a very rudimentary working example of the grid layout you described. It can probably be done a lot better, but this should get you started. (Particularly the switchOffenseDefense function and the switch_button button).
import Tkinter as tk
base=tk.Tk() #this is the main frame
root=tk.Frame(base) #Really this is not necessary -- the other widgets could be attached to "base", but I've added it to demonstrate putting a frame in a frame.
root.grid(row=0,column=0)
scoreboard=tk.Frame(root)
scoreboard.grid(row=0,column=0,columnspan=2)
###
#Code to add stuff to scoreboard ...
# e.g.
###
scorestuff=tk.Label(scoreboard,text="Here is the scoreboard")
scorestuff.grid(row=0,column=0)
#End scoreboard
#Start cards.
cards=tk.Frame(root)
cards.grid(row=1,column=0)
###
# Code to add pitcher and batter cards
###
clabel=tk.Label(cards,text="Stuff to add cards here")
clabel.grid(row=0,column=0)
#end cards
#Offense/Defense frames....
offense=tk.Frame(root)
offense.grid(row=1,column=1)
offense.isgridded=True #Dynamically add "isgridded" attribute.
offense_label=tk.Label(offense,text="Offense is coolest")
offense_label.grid(row=0,column=0)
defense=tk.Frame(root)
defense.isgridded=False
defense_label=tk.Label(defense,text="Defense is coolest")
defense_label.grid(row=0,column=0)
def switchOffenseDefense():
print "Called"
if(offense.isgridded):
offense.isgridded=False
offense.grid_forget()
defense.isgridded=True
defense.grid(row=1,column=1)
else:
defense.isgridded=False
defense.grid_forget()
offense.isgridded=True
offense.grid(row=1,column=1)
switch_button=tk.Button(root,text="Switch",command=switchOffenseDefense)
switch_button.grid(row=2,column=1)
root.mainloop()

Categories

Resources