'MultiColumnListbox' object has no attribute 'curselection' - python

I am running into an error with my MultiColumnListbox. I am trying to understand how to fix this issue. I am trying to see what is selected in my multicolumn listbox. The mutlicolumn listbox is built using tkinter and has a submit button which should run a function telling me what rows were selected in the multi column listbox. I am receiving this error 'MultiColumnListbox' object has no attribute 'curselection' and cant seem to fix it.
This is my code
import os
import time
import glob
import datetime
from array import *
try:
import Tkinter as tk
import tkFont
import ttk
except ImportError: # Python 3
import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
class MultiColumnListbox(object):
"""use a ttk.TreeView as a multicolumn ListBox"""
def submitFunction():
selection = listbox.curselection()
for k in range(0,len(selection)):
selected = listbox.curselection()[k]
def __init__(self):
self.tree = None
self._setup_widgets()
self._build_tree()
def _setup_widgets(self):
s = """\click on header to sort by that column
to change width of column drag boundary
"""
msg = ttk.Label(wraplength="4i", justify="left", anchor="n",
padding=(10, 2, 10, 6), text=s)
msg.pack(fill='x')
container = ttk.Frame()
container.pack(fill='both', expand=True)
# create a treeview with dual scrollbars
self.tree = ttk.Treeview(columns=car_header, show="headings")
vsb = ttk.Scrollbar(orient="vertical",
command=self.tree.yview)
hsb = ttk.Scrollbar(orient="horizontal",
command=self.tree.xview)
self.tree.configure(yscrollcommand=vsb.set,
xscrollcommand=hsb.set)
self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
vsb.grid(column=1, row=0, sticky='ns', in_=container)
hsb.grid(column=0, row=1, sticky='ew', in_=container)
container.grid_columnconfigure(0, weight=1)
container.grid_rowconfigure(0, weight=1)
def _build_tree(self):
for col in car_header:
self.tree.heading(col, text=col.title(),
command=lambda c=col: sortby(self.tree, c, 0))
# adjust the column's width to the header string
self.tree.column(col,
width=tkFont.Font().measure(col.title()))
for item in car_list:
self.tree.insert('', 'end', values=item)
# adjust column's width if necessary to fit each value
for ix, val in enumerate(item):
col_w = tkFont.Font().measure(val)
if self.tree.column(car_header[ix],width=None)<col_w:
self.tree.column(car_header[ix], width=col_w)
def sortby(tree, col, descending):
"""sort tree contents when a column header is clicked on"""
# grab values to sort
data = [(tree.set(child, col), child) \
for child in tree.get_children('')]
# if the data to be sorted is numeric change to float
#data = change_numeric(data)
# now sort the data in place
data.sort(reverse=descending)
for ix, item in enumerate(data):
tree.move(item[1], '', ix)
# switch the heading so it will sort in the opposite direction
tree.heading(col, command=lambda col=col: sortby(tree, col, \
int(not descending)))
FilesToDeleteName = [];
FilesToDeletePath = [];
FilesToDeleteDate = [];
car_list = [];
car_list.append([])
car_list.append([])
#str1 = input("Enter number of days old: ")
#days = int(str1)
days = 90
count = 0
time_in_secs = time.time() - (days * 24 * 60 * 60)
extf = ['Windows','Program Files', 'Program Files (x86)']
for (root, dirs, files) in os.walk('C:/Users', topdown=True):
dirs[:] = [d for d in dirs if d not in extf]
for filename in files:
Fullname = os.path.join(root,filename)
stat = os.stat(Fullname)
modified = datetime.datetime.fromtimestamp(stat.st_mtime)
if Fullname.endswith('.pcapng') or Fullname.endswith('.evtx') or Fullname.endswith('.png') or Fullname.endswith('.sql') or Fullname.endswith('.etl') or Fullname.endswith('.zip'):
if stat.st_mtime <= time_in_secs:
FilesToDeleteName.append(filename);
FilesToDeletePath.append(Fullname);
FilesToDeleteDate.append(str(modified));
FilesToDelete = [];
for p in range(0,len(FilesToDeletePath)):
STR2 = FilesToDeletePath[p],FilesToDeleteDate[p]
FilesToDelete.append(STR2)
car_list = FilesToDelete
car_header = ["Path ", "Date Modified"]
if __name__ == '__main__':
window = tk.Tk()
window.title("Multicolumn Treeview/Listbox")
listbox = MultiColumnListbox()
def submitFunction():
print(listbox.curselection(self))
window.destroy()
def closeFunction():
window.destroy()
submit = tk.Button(window, text='Submit', command=submitFunction)
submit.pack(side=tk.RIGHT, padx = 20)
close = tk.Button(window, text='Close', command=closeFunction)
close.pack(side=tk.RIGHT)
window.mainloop()
This is the main part of my issue
def submitFunction():
print(listbox.curselection(self))
window.destroy()
I will ultimately be trying to get the index numbers to delete the given file path

Related

Scaling grid contents in TkInter with complex structure

I have a tkInter window with a grid in it where each sell is containing several widgets. I want to make the window scalable and make grid cells scale accordingly:
import tkinter as tk
import math
def generate_pod(index, row, col, pod_list):
index = index
# Creating a pod and adding to the grid
pod_frame = tk.Frame(grid_window, borderwidth=0.5, relief="solid")
pod_frame.grid(row=row + 1, column=col)
# Create photoimage
img = tk.PhotoImage(width=160, height=90)
# Create a label diff image
img_label = tk.Label(pod_frame, image=img)
img_label.image = img # Keep a reference to prevent garbage collection
table_button = tk.Label(pod_frame, text=str(index))
score_frame = tk.Frame(pod_frame)
# Create a labels
ssim_label = tk.Label(score_frame, text='Sim: ')
# Movement
move_label = tk.Label(score_frame, text='Movement')
# Brightness
bright_label = tk.Label(score_frame, text='Brigh: ')
# Focus
sharp_label = tk.Label(score_frame, text='Foc: ')
alert_pod = tk.Label(alert_window, text=str(index))
# Add the labels to the pod
img_label.pack(side='top')
score_frame.pack(side='bottom')
table_button.pack(side='bottom')
ssim_label.grid(row=1, column=1)
move_label.grid(row=1, column=2)
bright_label.grid(row=2, column=1)
sharp_label.grid(row=2, column=2)
alert_pod.pack(side='top')
def refresh_pods(grid_rows, grid_cols):
# Destroy any existing widgets in the grid_window
for widget in grid_window.winfo_children():
widget.destroy()
pod_list = []
# Create a grid
for row in range(grid_rows):
for col in range(grid_cols):
# Calculate the index of the current pod
index = row * grid_cols + col
grid_window.rowconfigure(row, weight=1)
grid_window.columnconfigure(col, weight=1)
try:
generate_pod(index, row, col, pod_list)
except Exception as e:
print(e)
# Composing header
header_text = 'Header'
header = tk.Label(grid_window, text=header_text)
header.grid(row=0, column=0, columnspan=grid_cols)
# Schedule the refresh_pods() function to be called again in 2 min
main_window.after(120000, lambda: refresh_pods(grid_rows, grid_cols))
# Getting count of tables and count grid size
table_count = 50
grid_cols = math.floor(math.sqrt(table_count) * 1.2)
grid_rows = math.ceil(table_count/grid_cols)
grid_cols = int(grid_cols)
grid_rows = int(grid_rows)
# Create the main window
main_window = tk.Tk()
main_window.title('CDN snapshots aplha ver')
main_window.eval('tk::PlaceWindow . center')
main_window.resizable(True, True)
# Create a frame for the pods
grid_window = tk.Frame(main_window)
grid_window.pack(side='left', anchor='nw')
alert_window = tk.Frame(main_window)
alert_window.pack(side='right')
# Show the first page of pods
refresh_pods(grid_rows, grid_cols)
# Run the main loop
main_window.mainloop()
I found this snippet in the web that is working as I intend, but I failed to apply it to my code, mostly because all pod generation happens in functions and I didn't manage to pass arguments to labels and vice versa label list out of function
import tkinter as tk
import tkinter.font as tkFont
root = tk.Tk()
label_list = []
font = tkFont.Font(family="Helvetica")
pixel = tk.PhotoImage(width=100, height=1)
for x in range(3):
for y in range(3):
root.rowconfigure(y, weight=1)
root.columnconfigure(x, weight=1)
label_list.append(tk.Label(root, width=40, height=40, image=pixel, relief="groove", compound="center"))
label_list[-1].grid(row=x, column=y, sticky="nsew")
def font_resize(event=None):
for lbl in label_list:
x = lbl.winfo_width()
y = lbl.winfo_height()
root.bind( "<Configure>", font_resize)
root.mainloop()

tkinter highlight words by button clicks in Scrolledtext

I am trying to move to the next found word in the Scrolledtext and highlight it. The function finds indexes, but somehow I don't see the highlighting. The word is always the same. The search is in the dictionary text. There are usually many instances of the same word in the dictionary. The function see() is tied to a button. I use the highlight_word() in another function that is called see(), that function allows to move from word to word in the Scrolledtext and updates count of the words in a label. And this combination of functions does not work together...
UPDATE.
Thanks to hints from Bryan Oakley and in particular his hint which I found here. text.tag_remove The script now does what I want: it highlights the found word, and when the next found word is highlighted the highlight on the previous word is removed.
import tkinter as tk
import tkinter.font as TkFont
from tkinter import *
from tkinter.scrolledtext import ScrolledText
root = tk.Tk()
customFont = TkFont.Font(family="Fira Code", size=28)
var = tk.StringVar()
root.configure(bg='#3541b7')
root.geometry("1800x1000")
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
show = tk.IntVar()
show.set(0)
countVar = tk.StringVar()
idxVar = tk.StringVar()
posis = []
text = ScrolledText(root, width=140, height=400, wrap=WORD)
text.configure(background="#3f3f3f", fg='#dcdccc', font=customFont)
text.grid(row=1, columnspan=20, sticky=N + S + W + E)
text_to_search = '''
tempo
tempo
tempo
'''
text.insert(END, text_to_search)
entry_newwindow = tk.Entry(root, font=('Arial', 30), bg="#ffc299", bd=2)
IDX = "1.0"
prev_IDX = ""
prev_lastIDX = ""
def highlight_word():
global IDX
global prev_IDX
global prev_lastIDX
prev_IDX = ""
word = entry_newwindow.get().strip()
IDX = text.search(word, IDX, nocase=1, stopindex=END)
prev_IDX = IDX
lastIDX = '%s+%dc' % (IDX, len(word))
prev_lastIDX = lastIDX
text.tag_add('word', IDX, lastIDX)
text.tag_config('word', background='blue')
IDX = lastIDX
def see():
word = entry_newwindow.get().strip()
pos = show.get()
lbl_Count.config(text=f'{pos + 1}')
if prev_IDX and prev_lastIDX:
text.tag_remove("word", prev_IDX, prev_lastIDX)
highlight_word()
show.set(pos + 1)
btn_see = tk.Button(root, text='Find', fg='white', bg='#1E7056', font=(
'Fira Code', 21), borderwidth=' 4', command=see)
lbl_Count = tk.Label(root, font=('Fira Code bold', 24),
bg="#81cbfe", borderwidth=4, width=3, relief="groove", text="0")
entry_newwindow.grid(column=0, row=0,sticky="we")
entry_newwindow.focus_set()
btn_see.grid(column=1, row=0)
lbl_Count.grid(column=2, row=0)
root.mainloop()

How do I make python tkinter widgets appear on the right side of a frame and grow left?

Current behavior, adding LabelFrame widgets (with their own label and picture children) into another Labelframe named "Test putting buffs..." The LabelFrame widgets are being added into the left side of the LabelFrame and "grow" to the right. Wanted behavior is for the widgets to appear on the right side of the frame and "grow" left.
Cannot seem to get there with anchor or sticky settings. How can this "grow-left" be done and still preserve the ability to sort by name or time remaining?
Current behavior gif:
Wanted behavior (mocked up with paint):
Code (took out the image stuff so files aren't needed to run):
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
import time
class MainFrame(tk.Frame):
def __init__(self, container):
super().__init__(container)
self.grid(column=0, row=0)
self.buffs_list_frames = []
self.button1 = ttk.Button(self)
self.button1['text'] = "Simulate frame list appended True Strike"
self.button1['command'] = lambda: self.buffs_frame_list_is_appended(["True Strike", time.time() + 9])
self.button1.grid(column=0, row=0)
self.button2 = ttk.Button(self)
self.button2['text'] = "Simulate frame list appended Bulls"
self.button2['command'] = lambda: self.buffs_frame_list_is_appended(["Bulls", time.time() + 1080])
self.button2.grid(column=0, row=1)
self.button0 = ttk.Button(self)
self.button0['text'] = "Simulate frame list appended Endurance"
self.button0['command'] = lambda: self.buffs_frame_list_is_appended(["Endurance", time.time() + 1080])
self.button0.grid(column=0, row=2)
self.button3 = ttk.Button(self)
self.button3['text'] = "Simulate frame list put into .grid() and displayed"
self.button3['command'] = lambda: self.buffs_display_nicely()
self.button3.grid(column=0, row=3)
self.button4 = ttk.Button(self)
self.button4['text'] = "START loops of time passing"
self.button4['command'] = lambda: self.buffs_loop_time_passing()
self.button4.grid(column=0, row=4)
self.test_label_frame = ttk.LabelFrame(self, text="Testing putting buffs into a frame with grid")
self.test_label_frame.grid(column=1, row=0)
def buffs_loop_time_passing(self):
for x in self.buffs_list_frames:
x.buff_timer.set(f"{x.buff_birthday - time.time():.1f}s")
if x.buff_birthday < time.time() + 6:
x['background'] = 'red'
if x.buff_birthday < time.time():
self.buffs_list_frames.remove(x)
x.destroy()
self.after(1000, self.buffs_loop_time_passing)
def buffs_frame_list_is_appended(self, added_buff):
""" makes the buff frame and adds to the list of frame widgets
"""
self.buff_frame = tk.LabelFrame(self.test_label_frame, borderwidth=1, text=added_buff[0][0:4], labelanchor="n")
# self.buff_frame.buff_image_reference = ImageTk.PhotoImage(Image.open(added_buff[2]))
# self.buff_frame.buff_image_label = ttk.Label(self.buff_frame, image=self.buff_frame.buff_image_reference)
# self.buff_frame.buff_image_label.image_keep = self.buff_frame.buff_image_reference
# self.buff_frame.buff_image_label.grid(column=0, row=0)
self.buff_frame.buff_birthday = added_buff[1]
self.buff_frame.buff_timer = tk.StringVar()
self.buff_frame.buff_timer.set(f"{self.buff_frame.buff_birthday - time.time():.1f}s")
self.buff_frame.buff_label = ttk.Label(self.buff_frame, textvariable=self.buff_frame.buff_timer)
self.buff_frame.buff_label.grid(column=0, row=1)
self.buffs_list_frames.append(self.buff_frame)
self.buffs_display_nicely()
def buffs_display_nicely(self):
""" takes the list of frames, sorts by name, and .grids()s them into the test frame
"""
self.buffs_list_frames = sorted(self.buffs_list_frames, key=lambda z: z['text'])
print(f"sorted? {self.buffs_list_frames}")
j = 0
for x in self.buffs_list_frames:
x.grid(row=0, column=j)
j += 1
class App(tk.Tk):
def __init__(self):
super().__init__()
# configure the root window
self.title('NWN Buff Watcher')
self.geometry('300x50')
if __name__ == "__main__":
app = App()
main_frame = MainFrame(app)
app.mainloop()
Try this (using #acw1668's suggestion):
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
import time
class MainFrame(tk.Frame):
def __init__(self, container):
super().__init__(container)
self.buffs_list_frames = []
self.buttons_frame = tk.Frame(self)
self.buttons_frame.pack(fill="both", side="left")
self.button1 = ttk.Button(self.buttons_frame, text="Simulate frame list appended True Strike",
command=lambda: self.buffs_frame_list_is_appended("True Strike", 9))
self.button1.grid(column=0, row=0)
self.button2 = ttk.Button(self.buttons_frame, text="Simulate frame list appended Bulls",
command=lambda: self.buffs_frame_list_is_appended("Bulls", 1080))
self.button2.grid(column=0, row=1)
self.button0 = ttk.Button(self.buttons_frame, text="Simulate frame list appended Endurance",
command=lambda: self.buffs_frame_list_is_appended("Endurance", 1080))
self.button0.grid(column=0, row=2)
#self.button3 = ttk.Button(self.buttons_frame, text="Order items", command=self.order_items)
#self.button3.grid(column=0, row=3)
self.button4 = ttk.Button(self.buttons_frame, text="START loops of time passing",
command=self.buffs_loop_time_passing)
self.button4.grid(column=0, row=4)
self.test_label_frame = ttk.LabelFrame(self, text="Testing putting buffs into a frame with grid")
self.test_label_frame.pack(side="right")
def buffs_loop_time_passing(self):
for x in self.buffs_list_frames:
x.buff_timer.set(f"{x.buff_birthday - time.time():.1f}s")
time_now = time.time()
if x.buff_birthday < time_now + 6:
x.config(bg="red")
if x.buff_birthday < time_now:
self.buffs_list_frames.remove(x)
x.destroy()
self.after(100, self.buffs_loop_time_passing)
def buffs_frame_list_is_appended(self, added_buff, time_alive):
""" makes the buff frame and adds to the list of frame widgets
"""
buff_frame = tk.LabelFrame(self.test_label_frame, borderwidth=1,
text=added_buff[:4], labelanchor="n")
# buff_frame.buff_image_reference = ImageTk.PhotoImage(Image.open(added_buff[2]), master=self)
# buff_frame.buff_image_label = ttk.Label(buff_frame, image=buff_frame.buff_image_reference)
# buff_frame.buff_image_label.image_keep = buff_frame.buff_image_reference
# buff_frame.buff_image_label.grid(column=0, row=0)
buff_frame.buff_birthday = time.time() + time_alive
buff_frame.buff_timer = tk.StringVar(master=self)
buff_frame.buff_timer.set(f"{buff_frame.buff_birthday - time.time():.1f}s")
buff_frame.buff_label = ttk.Label(buff_frame,
textvariable=buff_frame.buff_timer)
buff_frame.buff_label.grid(column=0, row=1)
self.buffs_list_frames.append(buff_frame)
self.order_items()
def order_items(self):
self.buffs_list_frames = sorted(self.buffs_list_frames, key=lambda z: z['text'], reverse=True)
for x in self.buffs_list_frames:
x.pack_forget()
x.pack(side="right")
class App(tk.Tk):
def __init__(self):
super().__init__()
# configure the root window
self.title("NWN Buff Watcher")
# self.geometry("300x50")
if __name__ == "__main__":
app = App()
main_frame = MainFrame(app)
main_frame.pack()
app.mainloop()
I made a few changes to your code. The main thing is that I removed buffs_display_nicely and instead added buff_frame.pack(side="right"). The side="right" tells tkinter to add the widgets from the right to the left.
Also you can improve your code by a lot if you add a class instead of using buff_frame.buff_birthday, buff_frame.buff_timer, ... Also it will make your life a lot easier

How do I align rows of two frames in tkinter?

I have two frames in tkinter. One of them has labels, while the other has text fields and buttons. When a user clicks a button, more fields get added horizontally in the second frame. Both frames are connected to one vertical scrollbar, and the second frame has its own horizontal scrollbar. How can I make it so the first row of the first frame is aligned with the first row of the second frame?
I would like the fields to be aligned with A, B, C labels
from tkinter import *
import pyodbc # Importing for storing in a DB
from tkinter import messagebox
import getpass
import os
from datetime import datetime
from tkinter import ttk
import win32com.client
import openpyxl
from openpyxl import load_workbook
from tkcalendar import Calendar, DateEntry
global totalItems
global itemNum
global sizeList
global typeList
global qtyList
global actualQtyList
actualQtyList=[]
itemNum=0
def myfunction(event):
#canvas.configure(scrollregion=canvas.bbox("all"),height=650)
canvas.configure(scrollregion=canvas.bbox("all"), height=630)
def myfunction2(event):
canvasForCustomers.configure(scrollregion=canvasForCustomers.bbox("all"),height=645,width=900)
def multiple_yview(*args):
canvas.yview(*args)
canvasForCustomers.yview(*args)
def addNewCustomer():
global totalItems
global itemNum
padxValue=0
lbFrame_Customer=ttk.LabelFrame(frameForOfferCreationFilter,text="Customer")
cb_customer=ttk.Combobox(lbFrame_Customer,state='readonly',values=customerList,width=6)
cb_customer.grid(row=0,column=0)
lbFrame_ShipDate=ttk.LabelFrame(frameForOfferCreationFilter,text="Ship Date")
cal_ShipDate=DateEntry(lbFrame_ShipDate)
cal_ShipDate.grid(row=0,column=0)
lbFrame_PackedDateRange=ttk.LabelFrame(frameForOfferCreationFilter,text="Packed Date Range")
cal_FromDate=DateEntry(lbFrame_PackedDateRange)
lb_hyphen=ttk.Label(lbFrame_PackedDateRange,text="-")
cal_ToDate = DateEntry(lbFrame_PackedDateRange)
cal_FromDate.grid(row=0,column=0)
lb_hyphen.grid(row=0,column=1)
cal_ToDate.grid(row=0,column=2)
lbFrame_Customer.grid(row=0,column=itemNum,columnspan=1,padx=padxValue)
lbFrame_ShipDate.grid(row=0,column=itemNum+1,columnspan=1,padx=padxValue)
lbFrame_PackedDateRange.grid(row=0,column=itemNum+2,columnspan=2,padx=padxValue)
lb_CaseSize = ttk.Label(frameForOfferCreationFilter, text="Case Size", justify="center").grid(row=1, column=itemNum,padx=padxValue)
if itemNum%2!=0:
padxValue=20
else:
padxValue=0
indexNum=0
if indexNum%2==0:
padyValue2=0
else:
padyValue2=5
# frameForOfferCreation=Frame(canvasForCustomers,bg='yellow')
# frameForOfferCreation.grid(row=2,column=0,columnspan=6)
for indexNum in range(totalItems):
txt_CaseSize = ttk.Entry(frameForOfferCreationItems, width=7)
txt_CaseSize.grid(row=indexNum, column=itemNum, padx=10+padxValue,pady=padyValue2,sticky=S)
if indexNum % 2 == 0:
padyValue2 = 4
else:
padyValue2 = 0
itemNum = itemNum + 7
root_1 = Tk()
w, h = root_1.winfo_screenwidth(), root_1.winfo_screenheight()
root_1.geometry("%dx%d+0+0" % (w, h))
root_1.title("Sales Allocation Application")
allItems=['A','B','C']
############################ Getting Customers
allCustomers=['X','Y','Z']
customerList=[]
for item in allCustomers:
customerList.append(item[0])
tab_parent = ttk.Notebook(root_1)
tab_parent.pack(expand=1, fill='both')
tab_OfferPage = ttk.Frame(tab_parent)
tab_EditPage=ttk.Frame(tab_parent)
# tab_AllOffers = ttk.Frame(tab_parent)
tab_parent.add(tab_OfferPage, text='Create New Offer')
tab_parent.add(tab_EditPage,text="Edit Existing Offers")
lbFrm_ExistingItems=ttk.LabelFrame(tab_OfferPage,text="Items")
lbFrm_ExistingItems.pack(expand=1,fill='both')
canvas = Canvas(lbFrm_ExistingItems,width=300,height=650) # ,bg="#F4F3F1") width 400
canvas.grid(row=0, column=0,sticky=N)
frameOfItems = Frame(canvas,bg='green')
scrollBar = ttk.Scrollbar(lbFrm_ExistingItems, orient="vertical", command=multiple_yview) # canvas.yview)
canvas.configure(yscrollcommand=scrollBar.set)
frameOfItems.bind("<Configure>", myfunction)
scrollBar.grid(row=0, column=0, sticky=N + S + W) # , sticky=N + S + W)
canvas.create_window((0, 0), window=frameOfItems, anchor='nw')
canvasForCustomers=Canvas(lbFrm_ExistingItems,bg="red",width=900)
canvasForCustomers.grid(row=0, column=1,sticky=N+S)
frameForOfferCreationItems=Frame(canvasForCustomers,bg='pink')
frameForOfferCreationItems.bind("<Configure>", myfunction2)
frameForOfferCreationFilter=Frame(canvasForCustomers,bg='yellow')
frameForOfferCreationFilter.bind("<Configure>", myfunction2)
canvasForCustomers.create_window((0,0),window=frameForOfferCreationFilter,anchor='nw')
canvasForCustomers.create_window((0,80),window=frameForOfferCreationItems,anchor='nw')
btn_addCustomer=ttk.Button(lbFrm_ExistingItems,text="Add\nCustomer",command=addNewCustomer).grid(row=0,column=2,sticky=N+E)
btn_loadExisting=ttk.Button(lbFrm_ExistingItems,text="Load Existing\nOpen Offers").grid(row=0,column=3,sticky=N+E)
totalItems=len(allItems)
scrollBarHorizontal = ttk.Scrollbar(lbFrm_ExistingItems, orient="horizontal", command=canvasForCustomers.xview)
canvasForCustomers.configure(xscrollcommand=scrollBarHorizontal.set)
scrollBarHorizontal.grid(row=1, column=1, sticky=E + W+S)
canvasForCustomers.configure(yscrollcommand=scrollBar.set)
qtyList=[]
for item in allItems:
qtyList.append(Label(frameOfItems,text=item[0]))
actualQtyList.append(item[0])
lb_Qty=ttk.Label(frameOfItems,text="Quantity").grid(row=0,column=1,pady=10)
lb_LineBreak=ttk.Label(frameOfItems,text=" ").grid(row=1,column=0,columnspan=4,pady=12)
##### Adding blank label to attempt alignement
rowNum=2
padyValue=7
for item in range(len(qtyList)):
qtyList[item].grid(row=rowNum,column=4,pady=padyValue)
rowNum=rowNum+1
if rowNum%2==0:
padyValue=7
else:
padyValue=0
root_1.mainloop()
Tkinter is a pretty low-level GUI framework. I'd suggest one of the libraries from here, as they will make your life a whole lot easier.

Add time delay from array to listbox (Tkinter)

import tkinter
from tkinter import *
import time
tclean = tkinter.Tk()
tclean.title("TempCleaner")
tclean.resizable(width=False,height=False)
frame = Frame(tclean,width ="400",height="100")
scrollbar = Scrollbar(tclean)
scrollbar.pack( side = RIGHT, fill = Y ,expand =FALSE)
db = Button (tclean,text="Discover")
cb = Button (tclean, text="Clean")
list = Listbox (tclean, width="50",height="20", yscrollcommand = scrollbar.set)
path1='random'
f=[]
try:
for(dirpath,dirnames,filenames) in walk(path1):
f.extend(filenames)
break
except Exception:
pass
def displayFiles():
for x in range(0,len(f)):
list.insert(x,f[x])
time.sleep(.1)
I'm trying to have a short delay with each insertion on the list for tkinter. It only seems to display it all at once. How can I achieve this?
You can use root.after() to execute function which will add one item to Listbox and execute itself later using after()
import tkinter as tk
import os
def get_files(path):
files = []
try:
for rootpath, dirnames, filenames in os.walk(path):
files.extend(filenames)
break
except Exception as ex:
print(ex)
return files
def add_file():
global index
if index < len(files):
lb.insert('end', files[index])
index += 1
root.after(100, add_file)
def discover():
global files
print('discover')
files = get_files('Desktop/')
index = 0
add_file()
def clean():
global index
print('clean')
lb.delete(0, "end")
index = 0
# --- main ---
files = []
root = tk.Tk()
frame = tk.Frame(root, width="400", height="100")
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side='right', fill='y', expand=False)
db = tk.Button(root, text="Discover", command=discover)
db.pack()
cb = tk.Button(root, text="Clean", command=clean)
cb.pack()
lb = tk.Listbox(root, width="50", height="20", yscrollcommand=scrollbar.set)
lb.pack()
root.mainloop()

Categories