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()
Related
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
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
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.
I'm having a peculiar problem when displaying a widget containing a tkinter.StringVar variable.
This happens whether or not I use frames to locate the variable.
In brief, I have three non-variable labels, one variable label, a progressbar and two buttons all gridded vertically (the button are side by side though (irrelevant but supplied for completeness).
When the variable is changed programmatically, concatenating a new character ('\n) and more text, the variable shows the extra lines, but duplicate progressbars and buttons are displayed:
(Separate images here).
Interesting note: This does not happen if the '\n' is not added.
import os
import sys
import time
import tkinter as tk
import tkinter.ttk as ttk
class rtGetPaths(tk.Frame):
"""
"""
def __init__(self, root):
tk.Frame.__init__(self, root)
self.root = root
# Get the system separator
self.path_sep = os.pathsep
# Find the root on the drive
self.root_id = os.path.abspath(os.sep)
self.data = [(os.path.join('C:', 'Program Files', 'App_1.exe')),
(os.path.join('C:', 'Program Files', 'App_2.exe')),
(os.path.join('C:', 'Program Files', 'App_3.exe')),
(os.path.join('C:', 'Program Files', 'App_4.exe'))
]
self.locns = []
self.root.title('Get Paths')
self.gpw_l1 = tk.Label(self.root, text='Searching for apps')
self.gpw_l2 = tk.Label(self.root, text='This may take some time')
self.gpw_l3 = tk.Label(self.root, text='Please be patient')
self.gpw_found_l_svar = tk.StringVar()
self.gpw_found_l_svar.set('')
self.gpw_found_l = tk.Label(self.root, textvariable=self.gpw_found_l_svar)
self.gpw_pb_ivar = tk.IntVar()
self.gpw_pb_ivar.set(0)
self.gpw_pb_length = 350
self.gpw_pb_max = 5
self.gpw_pb = ttk.Progressbar(self.root,
mode='determinate',
maximum=self.gpw_pb_max,
length=self.gpw_pb_length,
variable=self.gpw_pb_ivar)
self.gpw_exit_b = tk.Button(self.root,
text='Exit',
command=sys.exit)
self.gpw_continue_b = tk.Button(self.root,
text='Continue',
command=self.gpw_action_continue_b)
row = 0
self.gpw_l1.grid(row=row, columnspan=2)
row += 1
self.gpw_l2.grid(row=row, columnspan=2)
row += 1
self.gpw_l3.grid(row=row, columnspan=2)
row += 1
self.gpw_found_l.grid(row=row, columnspan=2)
row += 1
self.gpw_pb.grid(row=row, columnspan=2)
row += 1
self.gpw_exit_b.grid(row=row, column=0, sticky='ew')
self.gpw_continue_b.grid(row=row, column=1, sticky='ew')
self.gpw_found_l.grid_remove()
self.root.geometry('+100+200')
def gpw_action_continue_b(self):
"""
:return:
"""
for file in self.data:
lookfor = ''
if 'App_1.exe' in file:
lookfor = file
elif 'App_2.exe' in file:
lookfor = file
elif 'App_3.exe' in file:
lookfor = file
elif 'App_4.exe' in file:
lookfor = file
if lookfor != '':
self.locns.append(lookfor)
label = self.gpw_found_l_svar.get()
if 0 < self.gpw_pb_ivar.get() < 5:
label = label + '\n'
label = label + os.path.join(lookfor)
self.gpw_found_l_svar.set(label)
self.gpw_pb_ivar.set(self.gpw_pb_ivar.get() + 1)
if not self.gpw_found_l.winfo_viewable():
self.gpw_found_l.grid()
self.root.update_idletasks()
time.sleep(1)
self.gpw_continue_b['state'] = 'disabled'
self.gpw_pb_ivar.set(self.gpw_pb_max)
self.root.update_idletasks()
return
#==============================================================================
# MAIN (MAIN)
#==============================================================================
def main():
""" Run the app
"""
# # Create the screen instance and name it
root = tk.Tk()
app = rtGetPaths(root)
root.mainloop()
root.quit()
#==============================================================================
# MAIN (STARTUP)
#==============================================================================
if __name__ == '__main__':
# Run the function name main()
main()
Why is it doing this, and how do I stop it?
I'm not sure why this problem is occurring, but you can fix it by updating the progress bar each time you change the lable
The code:
def gpw_action_continue_b(self):
for file in self.data:
...
self.gpw_pb.update() # this fixes the problem
self.root.update_idletasks()
time.sleep(1)
Proof it works:
I am very new on Python and I have a problem.
I try to read my temperature sensor and set the Value in to my Tkinter GUI.
I don't know how to update my label LT with the new value if I update it with my Button B1.
I have tried everything from StringVar to get() and this stuff.
I hope you can help me to find my failure.
Here is my code:
from tkinter import *
import os
Main = Tk()
Main.title("Hauptmenü")
Main.geometry("500x400")
class Fenster():
def Credit():
messagebox.showinfo(title="Credits",message="created by T.N v0.1")
return
def Beenden():
pExit = messagebox.askyesno(title="Beenden",message="Möchten Sie\n wirklich beenden?")
if pExit > 0:
Main.destroy()
return
def auslesen(event):
file = open("/sys/bus/w1/devices/28-041635ad4cff/w1_slave")
inhalt = file.read()
trennwoerter = inhalt.split(" ")
Wert = (trennwoerter[20])
Temp = (Wert[2:4])
file.close()
labelauslesen = Label(Main,text="Aktuelle Temperatur :")
labelauslesen.pack()
LT = Label(Main,text=Inhalt)
LT.pack()
B1 = Button(Main,text="Temperatur auslesen")
B1.pack()
B1.bind("<Button-1>",auslesen)
menubar=Menu(Main)
filemenu = Menu(menubar)
filemenu.add_command(label="Sensoren auslesen")
filemenu.add_command(label="Diagram anzeigen")
filemenu.add_command(label="Credits",command = Credit)
filemenu.add_command(label="Beenden",command = Beenden)
menubar.add_cascade(label="Datei",menu=filemenu)
Main.config(menu=menubar)
mainloop()
A minimal example that you can adapt to your code.
import tkinter as tk
root=tk.Tk()
temp = 10.0
def update_temp():
global temp
temp += 1.3
tlabel['text'] = '%s degrees C' % round(temp, 1)
tlabel = tk.Label(root, text='unknown')
tbutton = tk.Button(root, text='new temp', command=update_temp)
tlabel.pack()
tbutton.pack()
root.mainloop()