Python tkinter cut down path but open as full directory - python

Here is my full Python code:
from tkinter import *
import glob
import os
from PIL import Image, ImageTk, ImageGrab
import tkinter as tk
import pyautogui
import datetime
#date & time
now = datetime.datetime.now()
root = tk.Tk()
root.title("SIGN OFF")
root.minsize(840, 800)
# Add a grid
mainframe = tk.Frame(root)
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
mainframe.pack(pady=100, padx=100)
# Create a Tkinter variable
tkvar = tk.StringVar(root)
# Directory
directory = "C:/Users/eduards/Desktop/work/data/to-do"
choices = glob.glob(os.path.join(directory, "*.jpg"))
tkvar.set('...To Sign Off...') # set the default option
# Dropdown menu
popupMenu = tk.OptionMenu(mainframe, tkvar, *choices)
tk.Label(mainframe, text="Choose your sign off here:").grid(row=1, column=1)
popupMenu.grid(row=2, column=1)
label2 = tk.Label(mainframe, image=None)
label2.grid(row = 4, column = 1, rowspan = 10)
# On change dropdown callback.
def change_dropdown(*args):
""" Updates label2 image. """
imgpath = tkvar.get()
img = Image.open(imgpath)
img = img.resize((240,250))
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
tk.Button(mainframe, text="Open", command=change_dropdown).grid(row=3, column=1)
def var_states():
text_file = open("logfile.txt", "a")
text_file.write("TIME: %s, USER: %s, One %d, Two %d\n" % (now,os.getlogin(), var1.get(), var2.get()))
text_file.close()
print("One %d, Two %d" % (var1.get(), var2.get()))
var1 = IntVar()
Checkbutton(mainframe, text="Ingredients present in full (any allergens in bold with allergen warning if necessary)", variable=var1).grid(column = 2, row=1, sticky=W)
var2 = IntVar()
Checkbutton(mainframe, text="May Contain Statement.", variable=var2).grid(column = 2, row=2, sticky=W)
var3 = IntVar()
Checkbutton(mainframe, text="Cocoa Content (%).", variable=var3).grid(column = 2, row=3, sticky=W)
var4 = IntVar()
Checkbutton(mainframe, text="Vegetable fat in addition to Cocoa butter", variable=var4).grid(column = 2, row=4, sticky=W)
var5 = IntVar()
Checkbutton(mainframe, text="Instructions for Use.", variable=var5).grid(column = 2, row=5, sticky=W)
var6 = IntVar()
Checkbutton(mainframe, text="Additional warning statements (pitt/stone, hyperactivity etc)", variable=var6).grid(column = 2, row=6, sticky=W)
var7 = IntVar()
Checkbutton(mainframe, text="Nutritional Information Visible", variable=var7).grid(column = 2, row=7, sticky=W)
var8 = IntVar()
Checkbutton(mainframe, text="Storage Conditions", variable=var8).grid(column = 2, row=8, sticky=W)
var9 = IntVar()
Checkbutton(mainframe, text="Best Before & Batch Information", variable=var9).grid(column = 2, row=9, sticky=W)
var10 = IntVar()
Checkbutton(mainframe, text="Net Weight & Correct Font Size.", variable=var10).grid(column = 2, row=10, sticky=W)
var11 = IntVar()
Checkbutton(mainframe, text="Barcode - Inner", variable=var11).grid(column = 2, row=11, sticky=W)
var12 = IntVar()
Checkbutton(mainframe, text="Address & contact details correct", variable=var12).grid(column = 2, row=12, sticky=W)
def user():
user_input = os.getlogin()
tk.Label(mainframe, text = user_input, font='Helvetica 18 bold').grid(row = 0, column = 1)
user()
def save():
# pyautogui.press('alt')
# pyautogui.press('printscreen')
# img = ImageGrab.grabclipboard()
# img.save('paste.jpg', 'JPEG')
var_states()
tk.Button(mainframe, text = "Save", command = save).grid(row = 20, column = 1)
root.mainloop()
When I run the code, there will be a dropdown of jpg files. Currently It shows the full directory like so:
I have created a post earlier on how to trim down the path and got something like this:
files = os.listdir("C:/Users/eduards/Desktop/work/data/to-do")
print(files)
But If I use that code above, it will not open the path when clicked open because it doesn't have the full path name.
What I am trying to do is, cut down the path name for display purposes and open the image by following the original full path.
As an example:
The current drop-down menu shows C:/Users/eduards/Desktop/work/data/to-do/img1.jpg
My desired result is img1.jpg but in the background open the whole path of above.
Copy comment: this is what I have tried
directory = os.path.splitdrive("C:/Users/eduards/Desktop/work/data/to-do")
choices = glob.glob(os.path.join(directory[1:], "*.jpg"))
, but says
expected str, bytes or os.Pathlike, not tuple.
Have added [1:] because the path is split into 2 and returning the 2nd part of it.

Question: Show only the filename in OptionMenu but get original full path from selection.
Create your own OptionMenu which holds from all images the full path in a dict and shows only the filename as options.
Define your own widget FileNameOptionMenu by inheriting from (tk.OptionMenu)
class FileNameOptionMenu(tk.OptionMenu):
def __init__(self, parent, directory, extension, callback):
Get from all images the full path and extract the filename.
Save every full path in a dict using the filename as key and the full path as value.
# Save result from `glob` in a `dict`
self.glob = {}
for fpath in glob.glob(os.path.join(directory, "*.{}".format(extension))):
filename, extension = os.path.splitext(os.path.split(fpath)[1])
self.glob[filename] = fpath
Define a variable which holds the selected option for later usage.
Init the inherited tk.OptionMenu with the list of the keys from the dict.
Pass the class method self.command as command=.
Save the callback for later usage.
self.selected = tk.StringVar(parent, 'Select a image...')
super().__init__(parent, self.selected, *list(self.glob),
command=self.command)
self.callback = callback
This class method get called on every click option selection.
On call, it calls the self.callback, which is ImageLabel.configure, with the full path of the selected option.
def command(self, val):
self.callback(image=self.glob.get(self.selected.get()))
Define your own widget ImageLabel by inheriting from (tk.Label).
This class extends the tk.Label.configure to handle .configure(image=<full path> instead of .configure(image=<image object>.
class ImageLabel(tk.Label):
def __init__(self, parent):
super().__init__(parent, image=None)
Overload the inherited class method tk.Label.configure.
Catch the name argument image= and replace the passed full path with a image object.
def configure(self, **kwargs):
key = 'image'
if key in kwargs:
# Replace the filepath with the image
fpath = kwargs[key]
img = Image.open(fpath)
img = img.resize((240, 250))
self._image = ImageTk.PhotoImage(img)
kwargs[key] = self._image
Call the original tk.Label.configure to show the image
super().configure(**kwargs)
Usage:
import tkinter as tk
from PIL import Image, ImageTk
import glob, os
class App(tk.Tk):
def __init__(self):
super().__init__()
self.label_image = ImageLabel(parent=self)
self.label_image.grid(row=2, column=0)
self.option_menu = \
FileNameOptionMenu(parent=self,
directory='C:/Users/eduards/Desktop/work/data/to-do',
extension='jpg',
callback=self.label_image.configure
)
self.option_menu.grid(row=0, column=0)
if __name__ == "__main__":
App().mainloop()
Tested with Python: 3.5

Related

How to validate if label text exists in tkinter in Python?

I'm new to python and I'm wondering how to validate if label text exists. I'm getting an error:
Below's my full code. You can see the function validate at the bottom, and I'm figuring out how to make the label work in if else condition.
import openpyxl, os
import glob
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
class Root(Tk):
def __init__(self):
super(Root, self).__init__()
#Add a widget title
self.title("Automated filling up of form in iPage")
#Set widget width and height
self.minsize(300, 200)
#Display browse button
self.displayForm()
def doubleQuote(self, word):
return '"%s"' % word
def displayForm(self):
#Display label frame
self.labelFrame = ttk.LabelFrame(self, text = "Open Excel File")
self.labelFrame.grid(column=1, row=2, pady=5, sticky=NW)
#Create browse button
self.button = ttk.Button(self.labelFrame, text = "Browse a File",command = self.openFileDialog)
self.button.grid(column=1, row=1, padx=5, pady=5)
ttk.Label(self, text="Cell From:").grid(column=0, row=0, padx=5)
ttk.Label(self, text="Cell To:").grid(column=0, row=1, padx=5)
self.cf = StringVar()
self.ct = StringVar()
self.cellFrom = ttk.Entry(self, textvariable=self.cf)
self.cellTo = ttk.Entry(self, textvariable=self.ct)
self.cellFrom.grid(column=1, row=0, pady=5)
self.cellTo.grid(column=1, row=1, pady=5)
self.cf.trace("w",self.validate)
self.ct.trace("w",self.validate)
self.submitBtn = ttk.Button(self, text='Submit', command=self.validate)
self.submitBtn.grid(column=1, row=3, pady=5, sticky=NW)
def openFileDialog(self):
#Create a file dialog
self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select A File", filetype =
[("Excel files", ".xlsx .xls")])
self.label = ttk.Label(self.labelFrame, text = "", textvariable=self.fl)
self.label.grid(column = 1, row = 2)
#Change label text to file directory
self.label.configure(text = self.filename)
self.label.trace("w",self.validate)
#Return tail of the path
self.trimmed = os.path.basename(self.filename)
#Pass tail variable
self.openSpreadsheet(self.trimmed)
def openSpreadsheet(self, tail):
#Open excel spreadsheet
self.wb = openpyxl.load_workbook(tail)
self.sheet = self.wb['Sheet1']
#Return data from excel spreadsheet
for rowOfCellObjects in self.sheet[self.cf.get():self.ct.get()]:
#Loop through data
for link in rowOfCellObjects:
#Remove www and firstlightplus.com text
self.cleanURL = link.value.replace("www.", " ").replace(".firstlightplus.com", "")
print(self.cleanURL)
def validate(self, *args):
#Retrieve the value from the entry and store it to a variable
if self.cf.get() and self.ct.get() and self.label["text"]:
print("normal")
self.submitBtn.config(state='normal')
else:
print("disabled")
self.submitBtn.config(state='disabled')
root = Root()
root.mainloop()
I believe the problem is the validate function can be called before the openFileDialog function. This way, the label attribute is being accessed before it has been created.
A simple solution would be initialize the attribute in the displayForm function:
def displayForm(self):
#Display label frame
self.labelFrame = ttk.LabelFrame(self, text = "Open Excel File")
self.labelFrame.grid(column=1, row=2, pady=5, sticky=NW)
self.label = None
# ... Rest of the code
And then, before accessing the attribute, test if it exists:
def validate(self, *args):
#Retrieve the value from the entry and store it to a variable
if self.cf.get() and self.ct.get() and self.label and self.label["text"]:
print("normal")
self.submitBtn.config(state='normal')
else:
print("disabled")
self.submitBtn.config(state='disabled')

How to attach delete function in Tkinter GUI

I am new to python & requesting help from experts in this community. I am trying to delete images from my Tkinter widget FrameLabel. I have followed many solutions provided on the StackOverflow, but unfortunately, I am unable to implement those solutions in my code. I need help in deleting the image I have uploaded on the window.
GUI working:
Click on Select
Browse the image
Upload the image
It will display in the LabelFrame shown as following:
frame3 = tk.LabelFrame(pw_right, bd=2, text='Uploaded images')
frame3.pack(side='left', anchor='nw')
Delete Button
DelButton = tk.Button(frame1, text ='Delete', command = button.on_click_del_button)
DelButton.grid(row=0, column=4)
Delete Function:
def on_click_del_button(self):
print('Delete button clicked')
image = self.paths[self.radio_var.get()]
if os.path.exists(image):
os.remove(image)
else:
print("The file does not exist")
Help required section: I need help in defining Delete Function i.e button.on_click_del_button
so that when I press delete. Tkinter deletes the selected image from the window.
Below is the GUI for the window:
I followed the suggestion followed by expert furas, But nothing is happening in the Tkinter window. Although all the print values are being displayed.
You don't have to load image to delete from disk - you need only path
image = self.paths[self.radio_var.get()]
and you have to use variable image, not string "image"
BTW: you don't need lambda to assing this function
command=button.on_click_del_button
and you don't need path='None', image='None' if you don't send values as arguments.
def on_click_del_button(self):
print('Delete button clicked')
image = self.paths[self.radio_var.get()]
if os.path.exists(image):
os.remove(image)
else:
print("The file does not exist")
To hide widget from window you have widget.pack_foger() and widget.grid_forget(). It hides so you can show it again using widget.pack() or widget.grid(...).
To remove widget from window and from memory - so you can't use it again - you have widget.destroy() like
self.radio_handle[0].destroy()
but you would have to know which radiobutton was selected 0, 1 or 2.
Maybe better use path to keep elements in dictionary, not on list
self.radio_handle[path] = radio_button
and later in on_click_del_button
self.radio_handle[path].destroy()
You could also use path as value in Radiobutton
tk.Radiobutton(..., value=path)
EDIT: It remove image from window.
I use StringVar() instead of IntVar()
self.radio_var = tk.StringVar()
and assign path as value in Radiobutton
Radiobutton(..., value=path)
so now it can return path instead of numer and it can be easier to find object in dictionary
self.radio_handle = dict()
Using list and numbers it could be problem because after removing element from list other elements change position on list and it could make problem.
Now I can add widget to dictionary
self.radio_handle[path] = (radio_button)
and the same way I can destroy it
def on_click_del_button(self):
print('Delete button clicked')
path = self.radio_var.get()
self.radio_handle[path].destroy()
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import cv2
from PIL import Image
from PIL import ImageTk
class Button:
def __init__(self, root, frame3):
self.root = root
self.frame3 = frame3
self.radio_var = tk.StringVar()
self.path_selected = '' # or None
self.paths = []
self.radio_handle = dict()
self.check_value = []
def on_click_select_button(self, fname_label):
print('select button clicked')
fileType = [('jpg/png file', ('*.jpg', '*.png'))]
self.path_selected = filedialog.askopenfilename(filetypes=fileType)
fname_label['text'] = os.path.basename(self.path_selected)
def on_click_upload_button(self, path='None', image='None'):
print('upload button clicked')
if path == 'None':
path = self.path_selected
else:
cv2.imwrite(path, image)
if path in self.paths:
messagebox.showerror('Upload Error', '"'
+ path
+ '"' + ' is already uploaded.')
else:
self.paths.append(path)
self.create_radio_button(path)
def on_click_show_button(self, method):
print('showButton clicked')
image = cv2.imread(self.paths[self.radio_var.get()])
file_name = os.path.basename(self.paths[self.radio_var.get()])
name, ext = os.path.splitext(file_name)
path = 'images/' + name + '_' + method + ext
def create_radio_button(self, path):
image = cv2.imread(path)
# image = cv2.resize(image,(120,120))
image = self.scale_to_height(image, 120)
image_tk = self.to_tk_image(image)
radio_button = tk.Radiobutton(self.frame3, image=image_tk,
value=path,
variable=self.radio_var)
self.radio_var.set('')
self.radio_handle[path] = (radio_button)
self.check_value.append(self.radio_var)
radio_button.grid(row=(len(self.radio_handle) - 1) // 3,
column=(len(self.radio_handle) - 1) % 3)
self.root.mainloop()
def to_tk_image(self, image_bgr):
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
image_pil = Image.fromarray(image_rgb)
image_tk = ImageTk.PhotoImage(image_pil)
return image_tk
def on_click_del_button(self):
print('Delete button clicked')
path = self.radio_var.get()
if path:
self.radio_handle[path].destroy() # remove widget from window
del self.radio_handle[path] # remove from dictionary
self.paths.remove(path) # remove path from list
self.radio_var.set('')
else:
print('Not selected')
#image = path # self.paths[self.radio_var.get()]
#if os.path.exists(image):
# os.remove(image)
#else:
# print("The file does not exist")
def scale_to_height(self, img, height):
scale = height / img.shape[0]
return cv2.resize(img, dsize=None, fx=scale, fy=scale)
if __name__ == '__main__':
os.makedirs('images', exist_ok=True)
root = tk.Tk()
root.title('Image GUI')
root.geometry('1280x960')
pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
pw_left.pack(side='left', anchor='nw')
pw_right = tk.Frame(root, relief='ridge', borderwidth=4)
pw_right.pack(side='left', anchor='nw')
frame1 = tk.Frame(pw_left, bd=2, relief="ridge")
frame1.pack()
frame2 = tk.LabelFrame(pw_left, bd=2, relief="ridge", text='options')
frame2.pack(anchor='nw')
frame3 = tk.LabelFrame(pw_right, bd=2, text='Uploaded images')
frame3.pack(side='left', anchor='nw')
button = Button(root, frame3)
# add label
label = tk.Label(frame1, text='File:')
label.grid(row=0, column=0)
# label to show file name
file_name_label = tk.Label(frame1, text='-----not selected-----', width=20, bg='white')
file_name_label.grid(row=0, column=1)
# file select button
select_button = tk.Button(frame1, text='select',
command=lambda: button.on_click_select_button(file_name_label))
select_button.grid(row=0, column=2)
# upload button
uploadButton = tk.Button(frame1, text='Upload',
command=lambda: button.on_click_upload_button())
uploadButton.grid(row=0, column=3)
DelButton = tk.Button(frame1, text='Delete', command=button.on_click_del_button)
DelButton.grid(row=0, column=4)
root.mainloop()

How to use class and self here to get two different entries?

With my current code, it does not matter whether I click on "Input Folder" - Change or "JukeBox" change the result always gets displayed in "JukeBox" entry. This is incorrect, using class and self how can I change the code to display result from "Input Folder" - Change in "Input Folder" entry and the result from "Jukbox" - Change in "Jukebox" entry?
Also, how can I save the selected folders to a file so that it is there on app exit and re open?
My code:
import os
from tkinter import *
from tkinter import filedialog
inPut_dir = ''
jukeBox_dir = ''
def inPut():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
inPut_dir = StringVar()
inPut_dir = os.path.abspath(opendir)
entry.delete(0, END)
entry.insert(0, inPut_dir)
def jukeBox():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='JukeBox')
jukeBox_dir = StringVar()
jukeBox_dir = os.path.abspath(opendir)
entry.delete(0, END)
entry.insert(0, jukeBox_dir)
root = Tk()
root.geometry("640x240")
root.title("Settings")
frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)
text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
text = Label(frametop, text="JukeBox").grid(row=6, column=2)
entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)
ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frametop, text="Change", command=jukeBox).grid(row=6, column=28)
ButtonC = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
ButtonD = Button(frameright, text="Cancel").grid(row=5, column=15)
frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)
root.mainloop()
See attached image:enter image description here
Your code has both:
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
and
entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)
with jukeBox_dir/row 6 overriding inPut_dir/row 5
Therefore, in def input:
where you have:
entry.insert(0, inPut_dir)
You'll get the result in row 5 (jukebox_dir)

How to store a file location into an entry widget - Tkinter

I'm having a trouble to store a file location into a entry widget for my script using Tkinter:
So far I was able to have a browse button working perfectly, however, I cannot assing the variable value that I created parent.filename to store the file location into a entry widget like the photo below shows:
My script following below:
from Tkinter import *
import ttk
from PIL import ImageTk, Image
import os
import Tkinter, Tkconstants, tkFileDialog
class arquivos:
def __init__(self, parent):
parent.title('TEXT MINING - HMB QA')
self.gif1 = PhotoImage(file = 'tteste.gif')
label1 = Label(image=self.gif1)
label1.image = self.gif1
label1.grid(row = 0, column = 0, rowspan=13, sticky=NW)
Label(parent, text='File URL:').grid(row=0, column=1, sticky='e')
self.v1=Entry(parent, width=90)
self.v1.grid(row=0, column=2, sticky='we',columnspan=8)
self.button3 = Button(parent, text = "Browse", command
=self.loadtemplate, width = 10, height=1)
self.button3.grid(row=0, column=10, columnspan=2, sticky='w')
Label(parent, text='Filter RO List:').grid(row=1, column=1,
sticky='e')
self.v2=Radiobutton(parent, text="YES", value=1)
self.v2.grid(row=1,column=2, columnspan=1, sticky='w')
parent=Tk()
arquivos(parent)
parent.mainloop(
Regarding the function loadtemplate follows the code:
def loadtemplate(self):
parent.filename = StringVar()
parent.filename = tkFileDialog.askopenfilename(initialdir = "/",title
= "Select file",filetypes = (("jpeg files","*.jpg"),("all
files","*.*")))
print parent.filename
self.v20 = Entry(parent, textvariable=parent.filename, width=90)
self.v20.grid(row=0,column=2, sticky='we',columnspan=8)
When I hit the Browse button a box pops out and I can select the file directory:
The variable parent.filename assigned to store the file location also works, however, I'm not able to store the variable value into the entry widget self.v1
Any help will be highly appreciated
As is you're overwriting StringVar instance on parent.filename with a destination string. Use set method to set the value of the variable class
object in parent.filename instead.
Replace:
parent.filename = tkFileDialog.askopenfilename(initialdir = "/",title
= "Select file",filetypes = (("jpeg files","*.jpg"),("all
files","*.*")))
with:
parent.filename.set(tkFileDialog.askopenfilename(initialdir = "/",title
= "Select file",filetypes = (("jpeg files","*.jpg"),("all
files","*.*"))))

Cannot create Entry widget with tkinter

I'm having some trouble creating an entry widget with tkinter. I've imported the necessary modules and have already created several buttons and check boxes. However I cannot figure out how to properly initialize the Entry. Here is my relevant code:
# Necessary Modules.------------------------------------------------------------
import win32com.client as win32
import re
from tkinter import *
from tkinter.filedialog import askopenfilename
import tkinter.messagebox
# Class for selecting the file.-------------------------------------------------
class FilenameClass():
def __init__(self):
self.location = 'User Import.txt'
def getFile(self, identity):
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('Text Document (.txt)', '.txt'),
('all files', '.*')]
self.filename = askopenfilename(**self.file_opt)
if self.filename:
if 'User Import' in identity:
self.location = self.filename
app.get_txt_File['bg'] = '#0d0'
user_file = open(self.filename, 'r')
user_total = user_file.read()
remove_lines = user_total.splitlines()
for user in remove_lines:
regex_tab = re.compile('\\t')
user_info = regex_tab.split(user)
app.users.append(user_info)
else:
app.loadButton['bg'] = '#e10'
# Main Class.-------------------------------------------------------------------
class Application(Frame, Tk):
def __init__(self, master=None):
Frame.__init__(self, master)
self.users = []
self.fileOBJtxt = FilenameClass()
self.createWidgets()
def createWidgets(self):
# Define the default values for the options for the buttons
# Grid layout options
self.rowconfigure(0, minsize=5)
self.width = 54
self.grid(padx=5)
self.loadButton_gopt = {'row':1,'column':1,'padx': 2, 'pady': 5}
self.loadButton_wopt = {'width': round(self.width),'bg':'#e10'}
self.loadButton()
self.trainingCheckBox()
self.signatureInput()
def loadButton(self):
'''Button that calls the filename class which allows the user to select
the text file they wish to use.'''
self.get_txt_File = Button(self, text="Load User List", \
command=lambda: self.fileOBJtxt.getFile('User Import'))
for key, value in self.loadButton_wopt.items():
self.get_txt_File[key] = value
self.get_txt_File.grid(**self.loadButton_gopt)
def trainingCheckBox(self):
self.training_var = IntVar()
self.training = Checkbutton(text="Include training video?", \
variable=self.training_var).grid(row=2, sticky=W)
def signatureInput(self):
Label(text="Signature Name").grid(row=4, sticky=W)
entry = Entry(bg='#fff', width=50)
entry.grid(row=4, column=1, columnspan=4)
# Initialization parameters.----------------------------------------------------
if __name__ == '__main__':
app = Application()
app.master.title('User Notification Tool')
app.master.geometry('405x550+100+100')
app.master.resizable(width=False, height=False)
app.mainloop()
I'm not seeing any tracebacks, but I can't seem to get my Entry box to show up. What am I doing wrong?
EDIT: added entire code.
The problem with your entry field is you have not told it what frame/window to be placed in.
Change:
entry = Entry(bg='#fff', width=50)
To:
entry = Entry(self, bg='#fff', width=50)
Make sure you always provide the window/frame that a widget is going to be placed in as the first argument. In this case it is self as self refers to a frame.
Keep in mind that your program will not be able to get() the string inside of your entry field because you have not defined it as a class attribute. So most likely you will need to change
This:
entry = Entry(bg='#fff', width=50)
entry.grid(row=4, column=1, columnspan=4)
To This:
self.entry = Entry(self, bg='#fff', width=50)
self.entry.grid(row=4, column=1, columnspan=4)
This change will be necessary in order for the rest of your application to be able to read or write to the entry widget.
Change
entry = Entry(bg='#fff', width=50)
to
entry = tk.Entry(bg='#fff', width=50)

Categories

Resources