_tkinter.TclError: bad window path name ".!checkbutton" - python

I am trying to create an app that finds certain fields from a checkbox list.
I am stuck at self.text.window_create("end", window=cb) while calling search function. Although it works fine when running the line in the __init__ it throws an error here.
import tkinter as tk
class App:
def search(self):
searched_field = self.search_box.get()
found_indexes = []
for i in range(len(self.name_list)):
if searched_field in self.name_list[i]:
found_indexes.append(i)
self.text.delete("1.0", "end")
for i in range(len(found_indexes)):
cb = self.check_buttons[found_indexes[i]]
self.text.window_create("end", window=cb)
self.text.insert("end", "\n")
def write_names(self):
name_file = "names.txt"
with open(name_file, "w") as file:
for name in self.returned_list:
file.write(name + "\n")
def __init__(self, root, name_list):
self.check_buttons = []
self.var_list = []
self.returned_list = []
self.name_list = name_list
self.start = 0
self.search_box = tk.Entry(root)
self.search_box.pack(side="top")
self.search_button = tk.Button(root, text='Search', command=self.search)
self.search_button.pack()
self.scroll_bar = tk.Scrollbar(orient="vertical")
self.text = tk.Text(root, width=20, height=10, yscrollcommand=self.scroll_bar.set)
self.scroll_bar.config(command=self.text.yview)
self.scroll_bar.pack(side="right", anchor="ne", fill="y")
self.text.pack(side="top", fill="both", expand=True)
for name in name_list:
var = tk.BooleanVar()
cb = tk.Checkbutton(text=name, padx=0, pady=0, bd=0, variable=var)
self.check_buttons.append(cb)
self.var_list.append(var)
for cb in self.check_buttons:
self.text.window_create("end", window=cb)
self.text.insert("end", "\n")
tk.Button(root, text='Write names', command=self.write_names()).pack()
tk.Button(root, text='Quit', command=root.quit).pack()
name_list = ["aaa", "bbbb", "cccc", "abcd"]
root = tk.Tk()
app = App(root, name_list)
root.mainloop()
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\RO100162\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/RO100162/Desktop/proiect/eoIUPS/scrollbar.py", line 19, in search
self.text.window_create("end", window=cb)
File "C:\Users\RO100162\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 3423, in window_create
+ self._options(cnf, kw))
_tkinter.TclError: bad window path name ".!checkbutton"

You need to pass in the tkinter root
cb = tk.Checkbutton(root, text=name, padx=0, pady=0, bd=0, variable=var)
Similar to your other buttons
self.search_button = tk.Button(root, text='Search', command=self.search)

When you delete the contents of the text widget, that causes the checkbuttons to be deleted as well.
This is from the official tcl/tk documentation on the text widget [1]:
The embedded window's position on the screen will be updated as the text is modified or scrolled, and it will be mapped and unmapped as it moves into and out of the visible area of the text widget. Each embedded window occupies one unit's worth of index space in the text widget, and it may be referred to either by the name of its embedded window or by its position in the widget's index space. If the range of text containing the embedded window is deleted then the window is destroyed. Similarly if the text widget as a whole is deleted, then the window is destroyed.

Related

Only using grid Tkinter but still getting TclError

So I just started using Google Colab and I keep getting this error:
TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
I'm trying to make a GUI window that takes in the information from the user and saves it.
Everything I've read online says that the issue is that I'm using pack() and grid(), but I'm only using grid(). The error starts when I first try to place my labels (sourceLabel).
I'm so confused, any help would be great.
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
from tkinter import *
except ImportError:
import Tkinter as tk
from Tkinter import *
#creates window
window = tk.Tk()
window.title("File Information")
window.rowconfigure([0,1], minsize=30)
window.columnconfigure([0, 1, 2, 3], minsize=30)
#this program opens the file with information and adds the new information to it
def saveInfo():
value = path.get()
loc = source.get()
recode = recoding.get()
#change name of file and will this make them see everything
#f = open("./info.txt", "a+")
#f.write("Source Data File Location: " + loc + ", Complete File Path: " + value + ", Is recoding of column names and/or values desired?: " + recode)
#f.flush()
#f.seek(0)
#content = f.read()
#print (content)
finalList = [value,loc,recode]
#f.close()
window.withdraw()
print (finalList)
return finalList
#creates a text label, fg=foreground and bg=background, theyre the locations of colors, width and height are measured by text units which are separate horizonatal and vertical
sourceLabel = tk.Label(
text="Source Data File Location:",
width = 21,
height=2)
#adds text to window
sourceLabel.grid(row=0,column=0)
#creates second label
pathLabel = tk.Label(
text="Complete File Path:",
width = 20,
height=2)
#adds text to window
pathLabel.grid(row=1,column=0)
#creates third label
sourceLabel = tk.Label(
text="Is recoding of column \n names and/or values \n desired:",
width = 20,
height=4)
#adds text to window
sourceLabel.grid(row=2,column=0)
#create dropdown for sources
source = StringVar(window)
source.set("Local") # default value
sourceOption = OptionMenu(window, source, "Local", "Google Drive", "One Drive")
sourceOption.grid(row=0,column=1,sticky="ew")
#adds path entry
path = tk.Entry(fg="black", bg="white", width=35)
#adds path to window
path.grid(row=1,column=1,sticky="ew")
#create dropdown for recoding
recoding = StringVar(window)
recoding.set("Yes") # default value
recodingOption = OptionMenu(window, recoding, "Yes", "No")
recodingOption.grid(row=2,column=1,sticky="new")
#creates the click to save button
button = tk.Button(
text="Click to Save",
width=10,
height=1,
bg="white",
fg="black", command=saveInfo
)
#adds Button to window
button.grid(row=4,column=1,sticky="w")
#runs window
window.mainloop()
window.destroy()
This is a very weird error you had here, I just re-wrote your code using the canvas and pack method, instead of a grid, rows, and columns. Just make sure you are using Python3x Just so none of these weird bugs resurface, hope this helps, you can play around with the x and y values at the bottom, and you can mess with the height and width values at the top when we set the canvas. Happy coding!
from tkinter import *
global path, source, recoding # Global Values so that save_info can get the values
# Creates window
root = Tk()
root.title("File Information")
# Canvas Creates the base layer for the window, so instead of l = Label(text="Test").grid(row=2, column=3)
# We would now do l = Label(text="Test")
# canvas.create_window(20, 30, anchor="nw", window=l)
canvas = Canvas(width=400, height=300)
canvas.pack(fill="both", expand=True)
# Canvas.pack() just finishes creating the canvas.
# This program opens the file with information and adds the new information to it.
def save_info():
global path, source, recoding
value = path.get()
loc = source.get()
recode = recoding.get()
# change name of file and will this make them see everything
# f = open("./info.txt", "a+")
# f.write("Source Data File Location: " + loc + ", Complete File Path: " + value + ", Is recoding of column names and/or values desired?: " + recode)
# f.flush()
# f.seek(0)
# content = f.read()
# print (content)
finalList = [value, loc, recode]
# f.close()
root.withdraw()
print(finalList)
return finalList
sourceLabel = Label(
text="Source Data File Location:",
width=21,
height=2)
pathLabel = Label(
text="Complete File Path:",
width=20,
height=2)
recoding_label = Label(
text="Is recoding of column \n names and/or values \n desired:",
width=20,
height=4)
source = StringVar(root)
source.set("Local") # default value
sourceOption = OptionMenu(root, source, "Local", "Google Drive", "One Drive")
path = Entry(fg="black", bg="white", width=35)
recoding = StringVar(root)
recoding.set("Yes") # default value
recodingOption = OptionMenu(root, recoding, "Yes", "No")
button = Button(
text="Click to Save",
width=10,
height=1,
bg="white",
fg="black", command=save_info
)
# Since we are now using canvas, we must add all the elements using canvas.create_window, the first int is the x value, 2nd is the y
# Just leave anchor always as nw, and windows need to equal the variable of the widget they need to add
canvas.create_window(0, 50, anchor="nw", window=sourceLabel)
canvas.create_window(0, 90, anchor="nw", window=pathLabel)
canvas.create_window(0, 140, anchor="nw", window=recoding_label)
canvas.create_window(150, 50, anchor="nw", window=sourceOption)
canvas.create_window(150, 90, anchor="nw", window=path)
canvas.create_window(150, 140, anchor="nw", window=recodingOption)
canvas.create_window(150, 225, anchor="nw", window=button)
root.mainloop()
# I refactored some of the variables so they would be unique

How can I return a variable from a function that is opening a file using filedialog after selecting a tkinter button?

All of the tutorials I have seen deomonstrate the tkinter filedialog.askopenfilename function by only using the information collected within the function that is linked to the tkinter button. I can pass information in the function, but I would like to pass variables (filepath, images, etc.) outside the function and have them update variables in my GUI.
I have commented out the location I would like to call the variables in main_gui_setup function below. Any help will be appreciated, as it has been very demoralizing not being able to open a file. If this problem persists, my future as a programmer may be limited to creating tic-tac-toe games or instructional videos for Youtube.
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog, messagebox
from PIL import ImageTk, Image # was import PIL.Image, PIL.ImageTk
import cv2
def main():
root = Tk()
window1 = Window(root, "X-ray Assist", "Give up")
return None
# can't pass by reference in python
class Window():
n = 0
file_path = ""
img1_info = ""
def __init__(self, root, title, message):
self.root = root
self.root.title(title)
#self.root.geometry(geometry)
self.screen_width = root.winfo_screenwidth()
self.screen_height = root.winfo_screenheight()
#self.root.attributes('-topmost', 1)
# SET APP WINDOW SIZE
scr_size_main = self.scr_size() # create instance of scr_size
self.root.geometry("%dx%d+%d+%d" % (self.root_width, self.root_height, self.root_x, self.root_y))
# CREATE MAIN WINDOW GUI
create_gui = self.main_gui_setup()
self.root.mainloop()
pass
def scr_size(self):
'''Reads monitor size and adjusts GUI frame sizes'''
self.root_width = int(self.screen_width*0.52)
self.root_height = int(self.screen_height*0.9)
self.root_x = int(self.screen_width*0.23)
self.root_y = int(self.screen_height*0.02)
self.img_ht_full = int(self.screen_height*0.82)
self.tools_nb_width = int(self.screen_width*0.22)
self.tools_nb_height = int(self.screen_height*0.48)
self.hist_nb_width = int(self.screen_width*0.22)
self.hist_nb_height = int(self.screen_height*0.23)
def open_image(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
self.file_path = filedialog.askopenfilename(initialdir='/', title='Open File',
filetypes=(('tif files', '*.tif'), ('all files', '*.*')))
self.file_path_label = ttk.Label(main_win, text=self.file_path)
self.file_path_label.grid(column=0, row=0, columnspan=1, sticky="nw", padx=(5,0), pady=1)
self.img1_8bit = cv2.imread(self.file_path, 0) #, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img1_8bit_resize = cv2.resize(self.img1_8bit, (self.img_ht_full, self.img_ht_full)) #, interpolation = cv2.INTER_CUBIC)
#self.img1_height, self.img1_width = self.img1_8bit.shape # not resized for screen
#img1_info = text = f"{self.img1_height} {self.img1_8bit.dtype} {self.img1_16bit.dtype}"
#print(self.img1_width, " x ", self.img1_height, " bitdepth = ", self.img1_8bit.dtype)
#img1_info = ttk.Label
#print(f"{self.img1_height} {self.img1_width} {self.img1_8bit.dtype}")
#img1_info.grid(column=3, row=1, columnspan=1, sticky="w", padx=(5,0), pady=1)
#img = io.imread(main_win.filename) #scikit
self.img1_16bit = cv2.imread(self.file_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img_canvas = tk.Canvas(self.root, width=self.img_ht_full, height=self.img_ht_full)
#self.img_canvas.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
#self.img_canvas.image = ImageTk.PhotoImage(image=Image.fromarray(self.img1_8bit_resize))
#self.img_canvas.create_image(0,0, image=self.img_canvas.image, anchor="nw")
# .create_line(x1, y1, x2, y2, fill="color")
#self.img_canvas.create_line((self.img_ht_full/2), 0, (self.img_ht_full/2), (self.img_ht_full), fill="yellow")
#self.img_canvas.create_line(0, (self.img_ht_full/2), (self.img_ht_full), (self.img_ht_full/2), fill="yellow")
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
image_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=self.img_ht_full, height=self.img_ht_full)
image_win.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
toolbar = ttk.Frame(main_win, borderwidth=5) #, width=1100, height=15)
toolbar.grid(column=0, row=0, columnspan=10, rowspan=1, sticky="nw", padx=20)
hist_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=300, height=200)
panel_info = ttk.Label(main_win, text=f"{self.screen_width} x {self.screen_height}")
panel_info.grid(column=5, row=1, columnspan=1, sticky="e", pady=1)
# SCROLL SLIDER AT BOTTOM
slider = ttk.Scrollbar(main_win, orient="horizontal")
slider.grid(column=1, row=13, columnspan=7, padx=5, pady=5, sticky="ew")
#X-RAY AND DETECTOR SETTINGS - will input these from separate class
kv = ttk.Label(main_win, text="125kV")
kv.grid(column=0, row=2, columnspan=1, padx=15, pady=5)
file_path_label = ttk.Label(main_win, text="No image loaded")
file_path_label.grid(column=1, row=1, columnspan=1, sticky="nw", padx=(5,0), pady=1)
# CREATE BUTTONS
open = ttk.Button(toolbar, text="Open", width=10, command=self.open_image)
open.grid(column=0, row=0)
save = ttk.Button(toolbar, text="Save", width=10)
save.grid(column=1, row=0)
b1 = ttk.Button(toolbar, text="1", width=10)
b1.grid(column=2, row=0)
b2 = ttk.Button(toolbar, text="2", width=10)
b2.grid(column=3, row=0)
pass
main()
You aren't thinking of event driven programming correctly. In event driven programming you have callbacks to the functions you defined. Let's look at your code:
def get_path(self):
...
self.path_label = ...
...
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
open = ttk.Button(main_win, text="Open", width=10, command=self.get_path)
open.pack()
# Problematic code:
# main_label = ttk.Label(main_win, self.path_label)
# main_label.pack()
When main_gui_setup is called it creates a frame and a button inside it. When the button is clicked it calls get_path which sets up the path_label variable. The problem that you were facing is that that as soon as you create your button (without waiting for the button to be pressed), you create the label called main_label.
For a simple fix to your problem try this:
def get_path(self):
...
self.file_path = ...
self.path_label = ...
...
def button_callback(self, main_win):
# set up
self.get_path()
# My guess is that you wanted `self.file_path` here instead of `self.path_label`
main_label = ttk.Label(main_win, self.file_path)
main_label.pack()
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
# I am using a lambda and passing in `main_win` because you haven't
# assigned it to `self` using `self.main_win = ...`
open = ttk.Button(main_win, text="Open", width=10, command=lambda: self.button_callback(main_win))
open.pack()
I am still confused by what You are trying to accomplish:
from tkinter import Tk, Button, Label, filedialog
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.open_file_btn = Button(self, text='Open', command=self.open_file)
self.open_file_btn.pack()
self.file_name = None
def open_file(self):
self.file_name = filedialog.askopenfilename()
Label(self, text=self.file_name).pack()
root = MainWindow()
root.mainloop()
I will explain what will happen here! (You can change the .askopenfilename() attributes obviously).
When the program opens the filedialog and You select a file, that file name will now get assigned to self.file_name and that variable can be used anywhere in the class.
also from what I have seen You should learn more about classes and PEP 8

Why does the while loop only end when I close the tkinter window?

I have a big problem with my code. I am a beginner and trying to program a vocabulary trainer with a gui but im already failing. I know my code is probably very bad but I am trying to understand the problem. Here is my code:
import tkinter as tk
vocabulary = []
translations = []
finished1 = False
finished2 = False
root = tk.Tk()
def savevocabulary():
vocabulary.append(vocabularyinput)
pleaseinputvocab.pack_forget()
vocabularyEntry.pack_forget()
vocabularyButton.pack_forget()
global finished1
finished1 = True
def savetranslations():
translations.append(translationinput)
pleaseinputtrans.pack_forget()
translationEntry.pack_forget()
translationButton.pack_forget()
global finished2
finished2 = True
def askingquestion():
whatis = tk.Label(root, text="What is " + vocabulary[0].get() + "in English?")
whatis.pack()
whatisinput = tk.StringVar()
whatisentry = tk.Entry(root, textvariable=whatisinput)
whatisentry.pack()
if whatisinput == translations[0]:
correct = tk.Label(root, text="Correct!")
correct.pack()
else:
false = tk. Label(root, text="False!")
false.pack()
while finished1 is False and finished2 is False:
pleaseinputvocab = tk.Label(root, text="Please enter a vocabulary into the field and then click Done")
pleaseinputvocab.pack()
vocabularyinput = tk.StringVar()
vocabularyEntry = tk.Entry(root, textvariable=vocabularyinput)
vocabularyEntry.pack()
vocabularyButton = tk.Button(root, text="Done", command=savevocabulary)
vocabularyButton.pack()
pleaseinputtrans = tk.Label(root, text="Please enter the translation into the field and then click Done")
pleaseinputtrans.pack()
translationinput = tk.StringVar()
translationEntry = tk.Entry(root, textvariable=translationinput)
translationEntry.pack()
translationButton = tk.Button(root, text="Done", command=savetranslations)
translationButton.pack()
root.mainloop()
askingquestion()
root.mainloop()
When I start the program then the i can fill in the a vocabulary and a translation but then the widgets should disappear and I should be asked to fill in the translation to the vocabulary. Instead nothing is happening and when I close the window, this message appears:
Traceback (most recent call last):
File "C:\Users\maxig\Documents\ll.py", line 63, in <module>
askingquestion()
File "C:\Users\maxig\Documents\ll.py", line 31, in askingquestion
whatis = tk.Label(root, text="What is " + vocabulary[0].get() + "in English?")
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 3148, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 2572, in __init__
self.tk.call(
_tkinter.TclError: can't invoke "label" command: application has been destroyed
That means that the function is called after the window is closed. Why is that the case?
It is not what it seems. The issue is not your while loop but root.mainloop(). This creates a loop inside the function which needs to be running until you close the window; that's how tkinter works.
You can instead call askingquestion() when the user clicks a button.
pleaseinputvocab = tk.Label(root, text="Please enter a vocabulary into the field and then click Done")
pleaseinputvocab.pack()
vocabularyinput = tk.StringVar()
vocabularyEntry = tk.Entry(root, textvariable=vocabularyinput)
vocabularyEntry.pack()
vocabularyButton = tk.Button(root, text="Done", command=savevocabulary)
vocabularyButton.pack()
pleaseinputtrans = tk.Label(root, text="Please enter the translation into the field and then click Done")
pleaseinputtrans.pack()
translationinput = tk.StringVar()
translationEntry = tk.Entry(root, textvariable=translationinput)
translationEntry.pack()
translationButton = tk.Button(root, text="Done", command=savetranslations)
translationButton.pack()
ask_button = tk.Button(root, text="Ask question", command=askingquestion)
ask_button.pack()
root.mainloop()
Also, in Python, variable names should follow the naming convention. Instead of translationButton, translation_button.

import error no module named tkinter issue for latest Python version 3.8.2

I have been trying to resolve the error:
ImportError: No module named tkinter
however no solutions from previous questions seem to be working at all.
I have tried :
sudo apt-get install python3-tk
and tkinter installed successfully, yet the issue remains.
I've tried making the t in tkinter uppercase as i'm using Python 3.8.2 yet that did not work.
I have also tried reinstalling/repairing Python as tkinter supposedly comes with the latest Python versions.
Attempting to open my file with python3 main.py results in the following error
Traceback (most recent call last):
File "main.py", line 95, in
window = Tk()
File "/usr/lib/python3.6/tkinter/init.py", line 2023, in init
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I have also tried installing tkinter through its installer for
Windows, the installer works yet I still have the same issue. I have also tried updating my pip. Running pip list does not display tkinter.
Below is my main.py file.
from tkinter import *
from tkinter import filedialog
from tkinter.ttk import Progressbar
import tkinter.font as font
import os.path
from modify_data_pandas import get_column_headings
from modify_data_pandas import scan_file
#Closes window
def close_window():
window.destroy()
#Function checks if the file exists, changes label
def is_valid(*args):
if os.path.isfile(input_file_path.get()):
valid_confirm_lbl.config(text="File Found!")
valid_confirm_lbl.config(fg="green")
return 1
else:
valid_confirm_lbl.config(text="File Not Found")
valid_confirm_lbl.config(fg="red")
return 0
#Sets progress bar value
def setbar(value):
progress_bar['value'] = value
#Gets the current selection in the list box
def add_selection():
if is_valid():
items = headers_listbox.curselection()
already_selected = headers_listbox_selected.get(0, END)
for item in items:
if headers[item] not in already_selected:
headers_listbox_selected.insert(END, headers[item])
#Gets the current selection in the list box
def remove_selection():
if is_valid():
items = headers_listbox_selected.curselection()
pos = 0
for i in items :
idx = int(i) - pos
headers_listbox_selected.delete(idx,idx)
pos = pos + 1
#Add all items in listbox to selection
def add_all():
if is_valid():
items = headers_listbox.get(0, END)
for item in items:
if item not in headers_listbox_selected.get(0, END):
headers_listbox_selected.insert(END, item)
#Remove all items in selection listbox
def remove_all():
if is_valid():
headers_listbox_selected.delete(0, END)
#Scans the file for sensitive data
def scan():
if is_valid():
print("Scan")
change_row, change_col, change_type = scan_file(input_file_path, headers_listbox_selected.get(0, END))
#Anonymizes the file
def anonymize():
if is_valid():
print("do anonymize")
#Opens file dialog to pick a csv file
def choose_file():
input_file_name = filedialog.askopenfilename(initialdir = "/", title = "Select file",filetypes = (("CSV files","*.csv"),))
input_file.delete(0, END)
input_file.insert(END, input_file_name)
#Analyzes the file for sensitive data
def analyze_file():
if is_valid():
headers_listbox.delete(0, END)
headers_listbox_selected.delete(0, END)
global headers
headers = get_column_headings(input_file_path)
#headers = list of column headings from selected file
for item in headers:
headers_listbox.insert(END, item)
#Call function that checks each cell for sensitive data
return 1
else:
return 0
#Configure GUI Window
window = Tk()
window.title("CSV Anonymizer")
window.geometry("413x800")
lbl_frame = Frame(window)
lbl_frame.grid(column=0, row=1)
listbox_lbl_frame = Frame(window)
listbox_lbl_frame.grid(column=0, row=5, pady=5)
listbox_frame = Frame(window)
listbox_frame.grid(column=0, row=6)
listbox_btn_frame = Frame(window)
listbox_btn_frame.grid(column=0, row=7)
listbox_btn_frame_2 = Frame(window)
listbox_btn_frame_2.grid(column=0, row=8)
#Label: "File:"
input_file_prompt = Label(lbl_frame, text="File:",anchor=W, justify=LEFT)
input_file_prompt.pack(side = LEFT)
input_file_prompt.config(width=20)
#Label: "File Not Found / File Found!"
valid_confirm_lbl = Label(lbl_frame, text="", anchor=E, justify=RIGHT)
valid_confirm_lbl.pack(side = RIGHT)
valid_confirm_lbl.config(width=20)
#Create stringvar so file path is verified upon change
input_file_path = StringVar()
#Text Field to display/enter Input File Name
input_file = Entry(window, textvariable=input_file_path, width=10)
input_file.grid(column=0, row=2, padx=20)
input_file.config(width=40)
#Checks if the file is valid upon change
input_file_path.trace_add("write", is_valid)
#Button: "Click to Select a File", opens file browser to select a file
choose_file_btn = Button(window, text = "Click to Select a File", command = choose_file)
select_btn_font = font.Font(family='Helvetica', size=20, weight='bold')
choose_file_btn['font'] = select_btn_font
choose_file_btn.grid(column = 0, row = 0, padx=20, pady=20)
choose_file_btn.config(height=3,width=30)
#Button: "Use This File", starts analyze_file func
use_file_btn = Button(window, text = "Use This File", command = analyze_file)
use_file_btn.grid(column = 0, row = 3, padx=20, pady=(8, 10))
use_file_btn.config(width=13, height=2)
#Label "Select the columns you would like to anonymize"
select_columns_lbl = Label(window, text="Select the columns you would like to anonymize")
bold_font = font.Font(family='Helvetica', size=15, weight='bold')
select_columns_lbl['font'] = bold_font
select_columns_lbl.grid(column=0, row=4)
select_columns_lbl.config(width=40)
#Labels state listbox titles
column_headings_lbl = Label(listbox_lbl_frame, text = "Column Headings")
column_headings_lbl.pack(side=LEFT)
column_headings_lbl.config(width=20)
selected_column_headings_lbl = Label(listbox_lbl_frame, text = "Selected")
selected_column_headings_lbl.pack(side=RIGHT)
selected_column_headings_lbl.config(width=20)
#Left listbox, shows column headings from selected file
headers_listbox = Listbox(listbox_frame, selectmode = MULTIPLE)
headers_listbox.pack(side=LEFT)
headers_listbox.config(width=20)
#Right listbox, shows selected column headings
headers_listbox_selected = Listbox(listbox_frame, selectmode = MULTIPLE)
headers_listbox_selected.pack(side=RIGHT)
headers_listbox_selected.config(width=20)
#Buttons to add and remove current selections from respective listboxes
add_selection_btn = Button(listbox_btn_frame, text = "Add Current Selection", command = add_selection)
add_selection_btn.pack(side=LEFT)
add_selection_btn.config(width=20)
remove_selection_btn = Button(listbox_btn_frame, text = "Remove Current Selection", command = remove_selection)
remove_selection_btn.pack(side=RIGHT)
remove_selection_btn.config(width=20)
#Buttons to add and remove all items from their respective listboxes
add_all_btn = Button(listbox_btn_frame_2, text = "Add All", command = add_all)
add_all_btn.pack(side=LEFT)
add_all_btn.config(width=20)
remove_all_btn = Button(listbox_btn_frame_2, text = "Remove All", command = remove_all)
remove_all_btn.pack(side=RIGHT)
remove_all_btn.config(width=20)
#Label "Select the columns you would like to anonymize"
get_suggestions_lbl = Label(window, text="Would you like to scan the file for sensitive data?")
get_suggestions_lbl['font'] = bold_font
get_suggestions_lbl.grid(column=0, row=9, pady=(15, 10))
get_suggestions_lbl.config(width=40)
#Button: "Scan File", starts scan_file func
get_suggestions_btn = Button(window, text = "Scan File", command = scan)
get_suggestions_btn.grid(column = 0, row = 10, pady=(0, 10))
get_suggestions_btn.config(width=20, height=2)
#Button: "Anonymize", starts anonymize func
anonymize_btn = Button(window, text = "Anonymize", command = anonymize)
anonymize_btn.grid(column = 0, row = 11, pady=(0, 10))
anonymize_btn.config(width=20, height=2)
progress_bar = Progressbar(window, orient = 'horizontal', length = 286, mode = 'determinate')
progress_bar.grid(column = 0, row = 12, pady =2)
progress_bar["maximum"] = 100
progress_bar["value"] = 0
#Button to quit the program
quit_btn = Button(window, text = "Quit", command = close_window)
quit_btn.grid(column = 0, row = 20)
quit_btn.config(width=10, height=2)
window.mainloop()
Any ideas?

Assigning /Storing Highlighted text as a variable in Tkinter Python on Ubuntu

I am writing a program in Python on Ubuntu, to import files from a folder then single Left click for Highlight the filename
I am trying to Store or Assign the highlighted text as as a variable?
Is there a python function that will allow me to capture the text that is currently highlighted with the single left click and store it as a variable?
Can you please guide me on how do I achieve this task?
import subprocess,os
from Tkinter import *
def text_click_callback(event):
# an event to highlight a line when single click is done
line_no = event.widget.index("#%s,%s linestart" % (event.x, event.y))
#print(line_no)
line_end = event.widget.index("%s lineend" % line_no)
event.widget.tag_remove("highlight", 1.0, "end")
event.widget.tag_add("highlight", line_no, line_end)
event.widget.tag_configure("highlight", background="yellow")
def viewFile():
tex.delete('1.0', END)
for f in os.listdir(path):
linkname="link-" + f
tex.insert(END,f + "\n", linkname)
tex.tag_configure(linkname, foreground="blue", underline=True)
tex.tag_bind(linkname, "<Button-1>", text_click_callback ) # highlight a line
if __name__ == '__main__':
root = Tk()
step = LabelFrame(root,text="FILE MANAGER", font = "Arial 20 bold italic")
step.grid(row=1, columnspan=7, sticky='W',padx=100, pady=5, ipadx=130, ipady=25)
Button(step, text="ViewFile", font = "Arial 8 bold italic", activebackground="turquoise", width=30, height=5, command=viewFile).grid (row= 6, column =3)
Button(step, text="Exit", font = "Arial 8 bold italic", activebackground="turquoise", width=20, height=5, command=root.quit).grid (row= 6, column =5)
tex = Text(master=root) # TextBox For Displaying File Information
scr=Scrollbar(root,orient =VERTICAL,command=tex.yview)
scr.grid(row=8, column=2, rowspan=15, columnspan=1, sticky=NS)
tex.grid(row=8, column=1, sticky=E)
tex.config(yscrollcommand=scr.set,font=('Arial', 8, 'bold', 'italic'))
global process
path = os.path.expanduser("/tmp") # Define path To play, delete, or rename video
root.mainloop()
You can get the text using the same index that you use to highlight it:
the_text = event.widget.get(line_no, line_end)

Categories