tkinter python entry not being displayed - python-3.x

I have created a Form with labels and entries..but for some reason the entries are not being created,
peoplegui.py
from tkinter import *
from tkinter.messagebox import showerror
import shelve
shelvename = 'class-shelve'
fieldnames = ('name','age','job','pay')
def makewidgets():
global entries
window = Tk()
window.title('People Shelve')
form = Frame(window)
form.pack()
entries = {}
for (ix, label) in enumerate(('key',) + fieldnames):
lab = Label(form, text=label)
ent = Entry(form)
lab.grid(row=ix, column=0)
lab.grid(row=ix, column=1)
entries[label] = ent
Button(window, text="Fetch", command=fetchRecord).pack(side=LEFT)
Button(window, text="Update", command=updateRecord).pack(side=LEFT)
Button(window, text="Quit", command=window.quit).pack(side=RIGHT)
return window
def fetchRecord():
print('In fetch')
def updateRecord():
print('In update')
if __name__ == '__main__':
window = makewidgets()
window.mainloop()
When I run it the labels are created but not the entries.

You have forgetten to grid the entries.

Related

How to get input from tkinter Entry widget on second window while the first window continues to run

from tkinter import *
def first():
root1 = Tk()
Button(root1, text = 'get Second', command= second).pack()
root1.mainloop()
def second():
root2 = Tk()
user_input = StringVar()
Entry(root2, text = user_input).pack()
Button(root2, text = 'submit', command = lambda : print(user_input.get(), '\t printed')).pack()
root2.mainloop()
first()
You are making a few basic mistakes in here -
You if want to use a second window, it should be Toplevel not root Tk window. There should be only one root window in the program. This should act as parent to all the windows.
Its a good practice in most of the cases to define the widgets like Button, Entry separately and then pack() them.
Entry should have 'textvariable' not 'text'
Following is the updated code which may help you -
from tkinter import *
root = Tk()
def first():
button = Button(root, text = 'get Second', command= second)
button.pack()
root.mainloop()
def second():
window2 = Toplevel(root)
user_input = StringVar()
entry = Entry(window2, textvariable=user_input)
entry.pack()
button = Button(window2, text = 'submit', command = lambda: print(user_input.get()))
button.pack()
first()

python 3+ with tkinter: modal window not appearing

I'm new to python. I'm trying to set up a GUI with a main window and a modal window to receive the database credentials. The main window has to be in the background when the modal window appears and the user should not interact with it. Actually the application should terminate in case the user fails to provide a valid username and password. I'm presenting part of the code here. What I get is the main window (the modal window does not appear at all) and I can't do anything but shut the program down - not directly; only through visual studio.
'''
import tkinter as tk
class login:
def checkDbCredentials(self, user, password):
if (len(user)<4 or len(password)<4):
return 0
return 1
def ok(self):
us = self.user.get()
pw = self.password.get()
if self.checkDbCredentials(us, pw)==0:
tk.messagebox.showinfo("Error", "Username and Password do not match")
sys.exit(0)
self.dic['user']=us
self.dic['pass']=pw
self.win2.destroy()
def cancel(self, event=None):
self.parent.focus_set()
self.destroy()
def widgets(self):
x = self.win2.winfo_screenwidth()
y = self.win2.winfo_screenheight()
xx = int((x-270)/2)
yy = int((y-85)/2)
geo = "270x85+" + str(xx) + "+" + str(yy)
self.win2.geometry(newGeometry=geo)
self.tempLab= tk.Label(self.win2, text="Username:", pady=5)
self.tempLab1 = tk.Label(self.win2, text="Password:")
self.iuser = tk.Entry(self.win2, textvariable = self.user, width=30)
self.ipass = tk.Entry(self.win2, textvariable = self.password, width=30, show="*")
self.tempLab.grid(column=0, row=0)
self.tempLab1.grid(column=0, row=1)
self.iuser.grid(column=1, row=0)
self.ipass.grid(column=1, row=1)
self.bt = tk.Button(self.win2, text="Submit", command=lambda: self.ok())
self.bt.grid(column=0, row=2, columnspan=2, pady=5)
self.win2.bind("<Return>", self.ok)
self.win2.bind("<Escape>", self.cancel)
def __init__(self, dic, parent):
self.win2 = tk.Toplevel(parent)
self.parent=parent
self.dic = dic
self.user = tk.StringVar()
self.password = tk.StringVar()
self.win2.overrideredirect(1)
self.widgets()
self.win2.transient(parent)
self.win2.grab_set()
self.win2.protocol("WM_DELETE_WINDOW", self.cancel)
self.parent.wait_window(self.win2)
And the main class code is the following:
import tkinter as tk
from tkinter import ttk, X, Y, BOTH
from tkinter import messagebox
import sys
import login
class mainWindow:
def connect(bt, fr):
notImplementedYet()
def notImplementedYet():
msg = tk.messagebox
msg.showinfo("Warning", "Not Implemented yet!")
btX = 20
btY = 5
btSunken = '#aec2c2' # sunken button color
btRaised = '#85adad' # normal button color
rw = 0 # starting row for buttons
cl = 0 # starting column
dbCredentials = {"user":"", "pass":""}
win = tk.Tk()
win.title("Title")
win.geometry(newGeometry="1366x700+00+00")
win.iconbitmap(bitmap="bitmap.ico")
fr1 = tk.Frame(win, width=1366, height=50, background='beige')
fr1.grid(column=cl, row=rw, rowspan=5)
fr2 = tk.Frame(win)
fr2.grid(column=0, row=1)
lb2 = tk.Label(fr2, text="frame 2", background=btRaised)
btConnect = tk.Button(fr1, text="Connect", background = btRaised ,command=lambda: connect(btConnect, fr1), width=btX, height=btY)
btConnect.grid(column=0, row=0)
log = login.login(dbCredentials, win)
win.wait_window(log.win2)
print(dbCredentials)
win.mainloop()
win = mainWindow()
The question is why is the modal window not appearing? I've tried placing the 'wait_window' in the other class as well but it's still not working.

How to show images from path in new window in python tk

After browsing path of image i wanna show image on next window in python using Tk library but image is not showing in next window. please take a look on my code below and give answer Thanks.
import tkinter as tk
from tkinter import filedialog as fd
a=""
str1 = "e"
class Browse(tk.Frame):
""" Creates a frame that contains a button when clicked lets the user to select
a file and put its filepath into an entry.
"""
def __init__(self, master, initialdir='', filetypes=()):
super().__init__(master)
self.filepath = tk.StringVar()
self._initaldir = initialdir
self._filetypes = filetypes
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
a=self._entry
self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))
def _display_widgets(self):
self._label.pack(fill='y')
self._entry.pack(fill='x', expand=True)
self._button.pack(fill='y')
self._classify.pack(fill='y')
def retrieve_input(self):
#str1 = self._entry.get()
#a=a.replace('/','//')
print (str1)
def classify(self):
newwin = tk.Toplevel(root)
newwin.geometry("500x500")
label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
label.pack()
canvas = tk.Canvas(newwin, height=300, width=300)
canvas.pack()
my_image = tk.PhotoImage(file=a, master=root)
canvas.create_image(150, 150, image=my_image)
newwin.mainloop()
def browse(self):
""" Browses a .png file or all files and then puts it on the entry.
"""
self.filepath.set(fd.askopenfilename(initialdir=self._initaldir,
filetypes=self._filetypes))
if __name__ == '__main__':
root = tk.Tk()
labelfont = ('times', 10, 'bold')
root.geometry("500x500")
filetypes = (
('Portable Network Graphics', '*.png'),
("All files", "*.*")
)
file_browser = Browse(root, initialdir=r"C:\Users",
filetypes=filetypes)
file_browser.pack(fill='y')
root.mainloop()
Your global variable a which stores the path of the image is not getting updated. You need to explicitly do it. Below is the code that works. Have a look at the browse() function.
import tkinter as tk
from tkinter import filedialog as fd
a=""
str1 = "e"
class Browse(tk.Frame):
""" Creates a frame that contains a button when clicked lets the user to select
a file and put its filepath into an entry.
"""
def __init__(self, master, initialdir='', filetypes=()):
super().__init__(master)
self.filepath = tk.StringVar()
self._initaldir = initialdir
self._filetypes = filetypes
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
a = self._entry
self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))
def _display_widgets(self):
self._label.pack(fill='y')
self._entry.pack(fill='x', expand=True)
self._button.pack(fill='y')
self._classify.pack(fill='y')
def retrieve_input(self):
#str1 = self._entry.get()
#a=a.replace('/','//')
print (str1)
def classify(self):
global a
newwin = tk.Toplevel(root)
newwin.geometry("500x500")
label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
label.pack()
canvas = tk.Canvas(newwin, height=300, width=300)
canvas.pack()
my_image = tk.PhotoImage(file=a, master=root)
canvas.create_image(150, 150, image=my_image)
newwin.mainloop()
def browse(self):
""" Browses a .png file or all files and then puts it on the entry.
"""
global a
a = fd.askopenfilename(initialdir=self._initaldir, filetypes=self._filetypes)
self.filepath.set(a)
if __name__ == '__main__':
root = tk.Tk()
labelfont = ('times', 10, 'bold')
root.geometry("500x500")
filetypes = (
('Portable Network Graphics', '*.png'),
("All files", "*.*")
)
file_browser = Browse(root, initialdir=r"~/Desktop", filetypes=filetypes)
file_browser.pack(fill='y')
root.mainloop()
P.S. Do change your initialdir. I changed it as I am not on Windows.

I am having trouble making an input text box that goes through a function and outputs test to an output textbox with Tkinter

im new to Python3.6.2
So I want a program that takes an input (Via text box from tkinter) and outputs a word in my custom "language"
with this function
def Mescre(n):
Words = (n)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
print(Words.translate(Mes))
and here's what i want the window to look like
from tkinter import*
root = Tk()
Mescre = Label(root, text="Input:")
English = Label(root , text="Output:")
label1.grid(row=0, sticky=E)
label2.grid(row=1, sticky=E)
entry1 = Entry(root)
entry2 = Entry(root)
entry1.grid = (row=0, column=1)
entry2.grid = (row=1, column=1)
root.mainloop()
if "hello" was in the Input text box, i want the output to be "coqqu" in the Output text box.
See my example below:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.sv = StringVar()
self.Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
self.entry = Entry(self.root, textvariable = self.sv)
self.label = Label(self.root)
self.entry.pack()
self.label.pack()
self.sv.trace("w", self.callback)
def callback(self, *args):
self.label.configure({"text": self.entry.get().translate(self.Mes)})
root = Tk()
App(root)
root.mainloop()
Here we define a StringVar() to be the value of the attribute textvariable for the Entry widget.
We then assign a callback to a trace() on the variable so that whenever the variable is updated (When someone types in the Entry) we call callback().
Within callback() we use configure() on the Label widget in order to set the text to equal the post translation version of the value of the Entry widget.
This creates a "live updating" translation effect.
Here's a basic example:
import tkinter as tk
root = tk.Tk()
def Mescre():
val = textfield.get()
Words = (val)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
print(Words.translate(Mes))
textfield = tk.Entry(root)
textfield.pack()
button = tk.Button(root, command=Mescre, text='Push')
button.pack()
root.mainloop()
Updated:
import tkinter as tk
root = tk.Tk()
def Mescre():
val = textfield.get()
Words = (val)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
translation = Words.translate(Mes)
#print(translation)
outputfield.delete(0, tk.END)
outputfield.insert(0, translation)
textfield = tk.Entry(root)
textfield.pack()
outputfield = tk.Entry(root)
outputfield.pack()
button = tk.Button(root, command=Mescre, text='Push')
button.pack()
root.mainloop()

How to add background image to my application in Tkinter?

The code picture needs to fit the screen size perfectly. I saw a bunch of tutorials but nothing seems to work.I tried adding a canvas but it covers half the screen.All my buttons go under the image itself not over it. It's getting on my nerves .
here's my code :
import tkinter as tk
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
w = Label(root, text="Send and receive files easily")
w.config(font=('times', 32))
w.pack()
def create_window():
window = tk.Toplevel(root)
window.geometry("400x400")
tower= PhotoImage(file="D:/icons/tower.png")
towlab=Button(root,image=tower, command=create_window)
towlab.pack()
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Bifrost v1.0")
self.pack(fill=BOTH, expand=1)
self.img1 = PhotoImage(file="D:/icons/download.png")
self.img2 = PhotoImage(file="D:/icons/upload.png")
sendButton = Button(self, image=self.img2)
sendButton.place(x=305, y=15)
receiveButton = Button(self, image=self.img1)
receiveButton.place(x=355, y=15)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
top = Toplevel()
msg = Message(top, text="This is a project developed by Aditi,Sagar and
Suyash as the final year project.",
font=('', '15'))
msg.pack()
top.geometry('200x200')
button = Button(top, text="Okay", command=top.destroy)
button.pack()
top.mainloop()
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()
Overlaying elements is tricky. I think this might be approximately what you're looking for. At least it's a start...
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
class Window:
def __init__(self, master=None):
tower = PIL.Image.open("Images/island.png")
master.update()
win_width = int(master.winfo_width())
win_height = int(master.winfo_height())
# Resize the image to the constraints of the root window.
tower = tower.resize((win_width, win_height))
tower_tk = ImageTk.PhotoImage(tower)
# Create a label to hold the background image.
canvas = Canvas(master, width=win_width, height=win_height)
canvas.place(x=0, y=0, anchor='nw')
canvas.create_image(0, 0, image=tower_tk, anchor='nw')
canvas.image = tower_tk
frame = Frame(master)
frame.place(x=win_width, y=win_height, anchor='se')
master.update()
w = Label(master, text="Send and receive files easily", anchor='w')
w.config(font=('times', 32))
w.place(x=0, y=0, anchor='nw')
master.title("Bifrost v1.0")
self.img1 = PhotoImage(file="Images/logo.png")
self.img2 = PhotoImage(file="Images/magnifier.png")
frame.grid_columnconfigure(0, weight=1)
sendButton = Button(frame, image=self.img2)
sendButton.grid(row=0, column=1)
sendButton.image = self.img2
receiveButton = Button(frame, image=self.img1)
receiveButton.grid(row=0, column=2)
receiveButton.image = self.img1
menu = Menu(master)
master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
message = "This is a project developed by Aditi,Sagar and"
message += "Suyash as the final year project."
messagebox.showinfo("Delete Theme", message)
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()

Resources