How to change state a self.button - python

i try to learn Object Oriendet with Tkinter.
i make a Button Class and try using this but i cant change it's state
this my class
class Buton():
def __init__(self, konum=None, text=None, command=None, cursor="hand2", state="normal", width=None,
row=None, column=None, sticky=None):
print("SELF: ", type(self), self)
self.konum = konum
self.text = text
self.command = command
self.cursor = cursor
self.state = state
self.width = width
self.row = row
self.column = column
self.sticky = sticky
self.buton_bas()
def buton_bas(self):
self.buton = Button(self.konum, text=self.text, state=self.state, command=self.command)
self.buton.grid(row=self.row, column=self.column, padx=2, pady=5)
def state_change(self, new_state):
self.['state'] = new_statew
My def and button
def print():
global label
label = Label(pencere, text=entry.get(), fg="lightgray", bg=darkbg, font=("Times 10"))
label.grid(row=3, column=0, columnspan=2, padx=2, pady=5, )
Buton.state_change(buton1, "disable")
buton1 = Buton(konum=pencere, text="Print", command=print, row=2, column=0)
When i push Print button, it print the text from entry. its ok but i cant change button's state. i take this: TypeError: 'Buton' object does not support item assignment
i try ;
self.state = new_state
but dont work.. what is wrong?
thanks for help from now

Your code contains a lot of errors. I have fixed them. You need to use <button>["state"] = state. Try:
from tkinter import *
root = Tk()
class Buton():
def __init__(self, konum=None, text=None, command=None, cursor="hand2", state="normal", width=None,
row=None, column=None, sticky=None):
#print("SELF: ", type(self), self)
self.konum = konum
self.text = text
self.command = command
self.cursor = cursor
self.state = state
self.width = width
self.row = row
self.column = column
self.sticky = sticky
self.buton_bas()
def buton_bas(self):
self.buton = Button(self.konum, text=self.text, state=self.state, command=self.command)
self.buton.grid(row=self.row, column=self.column, padx=2, pady=5)
def state_change(self, new_state):
self.buton['state'] = new_state
def print():
global label
label = Label(root, text="You can change text", fg="lightgray", bg="grey", font=("Times 10"))
label.grid(row=3, column=0, columnspan=2, padx=2, pady=5, )
Buton.state_change(buton1, "disable")
buton1 = Buton(konum=root, text="Print", command=print, row=2, column=0)

Related

Tkinter "_tkinter.TclError: image "pyimage1" doesn't exist" error

I'm trying to add an image to a frame in Tkinter but getting the error: _tkinter.TclError: image "pyimage1" doesn't exist.
I have a parent class that all of my windows inherit from:
class GUI(tk.Tk):
def __init__(self, name, dimensions):
super().__init__()
self.name = name
self.dimensions = dimensions
self.title(self.name)
self.geometry(self.dimensions)
The child class I want to add the image to is shown below(I have taken out some of the functions so that it isn't very long).
class Analyze(GUI):
def __init__(self, name, dimensions):
super().__init__(name, dimensions)
conn = sqlite3.connect('invoice_db.db')
cursor = conn.cursor()
self.frame1 = LabelFrame(self, text="Analyze Data")
self.frame1.grid(row=0, column=0, padx=10, pady=5)
self.frame2 = LabelFrame(self, text="Graph")
self.frame2.grid(row=1, column=0, padx=10, pady=5)
self.choices = ["", "", "", "", ""]
self.select_type = ttk.Combobox(self.frame1, value=("Credit", "Debit", "Net Profit"))
self.select_type.current(0)
self.select_type.bind("<<ComboboxSelected>>", self.click_type)
self.select_type.grid(row=0, column=0)
self.company_list = ["All Companies"]
cursor.execute("SELECT company_name FROM companies"),
self.companies = cursor.fetchall()
for x in self.companies: self.company_list.append(x[0])
self.select_company = ttk.Combobox(self.frame1, value=self.company_list)
self.select_company.current(0)
self.select_company.bind("<<ComboboxSelected>>", self.click_company)
self.select_company.grid(row=0, column=1)
self.start_date_calendar = DateEntry(self.frame1, date_pattern='y-mm-dd')
self.start_date_calendar.grid(row=0, column=2, padx=10, pady=10)
self.start_date_calendar.bind("<<DateEntrySelected>>", self.start_date)
self.end_date_calendar = DateEntry(self.frame1, date_pattern='y-mm-dd')
self.end_date_calendar.grid(row=0, column=3, padx=10, pady=10)
self.end_date_calendar.bind("<<DateEntrySelected>>", self.end_date)
self.currency_entry = Entry(self.frame1)
self.currency_entry.grid(row=0, column=4, padx=10, pady=10)
self.show_results_button = Button(self.frame1, text="Show Results", command=self.show_results)
self.show_results_button.grid(row=1, column=1, padx=10, pady=10)
self.go_back_button = Button(self, text="Go Back", command=self.go_back)
self.go_back_button.grid(row=0, column=0, padx=10, pady=10)
self.create_graph_button = Button(self.frame2, text="Create Graph", command=self.create_graph)
self.create_graph_button.pack()
conn.commit()
conn.close()
def create_graph(self):
image1 = Image.open("images/hop1.png")
img = ImageTk.PhotoImage(image1)
label1 = Label(self.frame2,image=img)
label1.image = img
label1.pack()
I call the Analyze class in another class like this:
class Welcome(GUI):
def __init__(self, name, dimensions):
super().__init__(name, dimensions)
# Create the starting label and buttons
self.title = Label(self, text="Invoice Organizer", font=("Helvetica", 36))
self.title.place(relx=.5, rely=.1, anchor="center")
self.company_button = Button(self, text="Companies", font=("Helvetica", 18), command=lambda: self.select_page("Company"))
self.company_button.place(relx=.3, rely=.5, anchor="center")
self.analyze_button = Button(self, text="Invoices", font=("Helvetica", 18), command=lambda: self.select_page("Invoice"))
self.analyze_button.place(relx=.5, rely=.5, anchor="center")
self.invoice_button = Button(self, text="Analyze", font=("Helvetica", 18), command=lambda: self.select_page("Analyze"))
self.invoice_button.place(relx=.7, rely=.5, anchor="center")
def select_page(self, button):
if button == "Company":
new = Company(button, "1000x800")
elif button == "Invoice":
new = Invoice(button, "1000x800")
else:
new = Analyze(button, "1000x800")

Is It possible to create multiple form fields in tkinter & python and then submit it to a out to an output textbox in a table column format

So my problem is that I want to create multiple entry fields like over 30, but every time I reformat it using .pack or .grid it keeps throwing off the formatting. is there a way to fit nearly 30 entry boxes on one window without using anything like SQLite? As we can see from this code, we have 4 fields, how would you go on with shrinking the boxes to put in more entry fields like over 30.
Secondly, I want to output all the typed data entry fields to the Listbox is there a way to add a table column to the list box to show a breakdown of each entry field.
The third is it possible to move the Listbox to another tab on the same window to show all entry fields that were typed in, if so how would you do so.
Here is my current code so far
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from datetime import *
# Import Packages
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.scrolledtext import *
import tkinter.filedialog
from tkcalendar import Calendar, DateEntry
from tkinter import messagebox
from tkintertable import TableCanvas, TableModel
from tkinter import ttk
# Database
#import sqlite3
import csv
window = Tk()
window.title("TESTTEST")
window.geometry("750x450")
window.config(background='black')
#style = ttk.Style(window)
#style.configure('lefttab.TNotebook', tabposition='wn',)
# TAB LAYOUT
#tab_control = ttk.Notebook(window,style='righttab.TNotebook')
#tab1 = ttk.Frame(tab_control)
#tab2 = ttk.Frame(tab_control)
#tab3 = ttk.Frame(tab_control)
#tab4 = ttk.Frame(tab_control)
#tab5 = ttk.Frame(tab_control)
#tab6 = ttk.Frame(tab_control)
# ADD TABS TO NOTEBOOK
#tab_control.add(tab1, text=f'{"Home":^20s}')
#tab_control.add(tab2, text=f'{"View":^20s}')
#tab_control.add(tab3, text=f'{"Search":^20s}')
#tab_control.add(tab4, text=f'{"Edit":^20s}')
#tab_control.add(tab5, text=f'{"Export":^20s}')
#tab_control.add(tab6, text=f'{"About ":^20s}')
#label1 = Label(tab1, text= 'Python RPA APP',padx=1, pady=1)
#label1.grid(column=0, row=0)
#label2 = Label(tab2, text= 'View',padx=5, pady=5)
#label2.grid(column=0, row=0)
#label3 = Label(tab3, text= 'Search',padx=5, pady=5)
#label3.grid(column=0, row=0)
#label4 = Label(tab4, text= 'Edit/Update',padx=5, pady=5)
#label4.grid(column=0, row=0)
#label5 = Label(tab5, text= 'Export',padx=5, pady=5)
#label5.grid(column=0, row=0)
#label6 = Label(tab6, text= 'About',padx=5, pady=5)
#label6.grid(column=0, row=0)
#tab_control.pack(expand=1, fill='both')
class Main(ttk.Frame):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.punches_list = []
self.ent1 = tk.StringVar()
self.ent2 = tk.StringVar()
self.ent3 = tk.StringVar()
self.ent4 = tk.StringVar()
self.init_ui()
def init_ui(self):
f = ttk.Frame()
# ttk.Label(f, text = "Entry1").pack(side=TOP, anchor=NW)
## ttk.Label(f, text = "Entry1").pack(side=LEFT, padx=5, pady=5, anchor=NW)
## self.txTest = ttk.Entry(f,textvariable=self.ent).pack(fill=X, padx=5, expand=True, anchor=NW)
# ttk.Label(f, text = "Entry1").pack(side=TOP, anchor=NW)
# self.txTest1 = ttk.Entry(f, textvariable=self.ent2).pack(side=TOP, anchor=NW)
ttk.Label(f, text = "Entry1").pack(side=TOP, anchor=NW, fill=tk.BOTH, pady=5, padx=5, expand=0)
self.txTest1 = ttk.Entry(f, textvariable=self.ent1).pack(side=TOP, anchor=NW, fill=tk.BOTH, pady=5, padx=5, expand=0)
ttk.Label(f, text = "Entry2").pack(side=TOP, anchor=NW,fill=tk.BOTH, pady=5, padx=5, expand=0)
self.txTest2 = ttk.Entry(f, textvariable=self.ent2).pack(side=TOP, anchor=NW,fill=tk.BOTH, pady=5, padx=5, expand=0)
ttk.Label(f, text = "Entry3").pack(side=TOP, anchor=NW,fill=tk.BOTH, pady=5, padx=5, expand=0)
self.txTest3 = ttk.Entry(f, textvariable=self.ent3).pack(side=TOP, anchor=NW,fill=tk.BOTH, pady=5, padx=5, expand=0)
#tkinter.Label(window, text = "Username").grid(row = 0) #'username' is placed on position 00 (row - 0 and column - 0)
#tkinter.Entry(window).grid(row = 0, column = 1) # first input-field is placed on position 01 (row - 0 and column - 1)
ttk.Label(f, text = "Entry4").pack(side=TOP, anchor=NW,fill=tk.BOTH, pady=5, padx=5, expand=0)
self.txTest4 = ttk.Entry(f, textvariable=self.ent4).pack(side=TOP, anchor=NW,fill=tk.BOTH, pady=5, padx=5, expand=0)
self.lstItems = self.get_listbox(f, 140,140).pack(anchor=N)
w = ttk.Frame()
ttk.Button(w, text="Add",command=self.add_In).pack(side=TOP, anchor=NE)
ttk.Button(w, text="Clear", command=self.clear_Out).pack(side=TOP, anchor=NE)
ttk.Button(w, text="Close", command=self.on_close).pack(side=TOP, anchor=NE)
#f.pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)
#w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)
f.pack(side=tk.LEFT, fill=tk.BOTH, pady=5, padx=5, expand=1)
w.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
def add_In(self,):
#s = "IN {0:>30} {1}".format(str(datetime.now()), self.ent.get())
s = self.ent1.get()
self.set_list(s)
s = self.ent2.get()
self.set_list(s)
s = self.ent3.get()
self.set_list(s)
s = self.ent4.get()
self.set_list(s)
self.ent1.set('')
self.ent2.set('')
self.ent3.set('')
self.ent4.set('')
def clear_Out(self):
#s = "OUT {0:>29} {1}".format(str(datetime.now()), self.ent1.get())
#field_name.set('')
self.ent1.set('')
self.ent2.set('')
self.ent3.set('')
self.ent4.set('')
#self.set_list(s)
def set_list(self,s):
self.punches_list.append(s)
self.lstItems.delete(0, tk.END)
for i in self.punches_list:
self.lstItems.insert(tk.END, i)
def on_set(self):
self.check.set(1)
def on_close(self):
#self.destroy()
self.parent.on_exit()
def get_listbox(self, container, height=750, width=600):
sb = tk.Scrollbar(container,orient=tk.VERTICAL)
w = tk.Listbox(container,
relief=tk.GROOVE,
selectmode=tk.BROWSE,
height=height,
width=width,
background = 'white',
font='TkFixedFont',
yscrollcommand=sb.set,)
sb.config(command=w.yview)
w.pack(side=tk.LEFT,fill=tk.BOTH, expand =1)
sb.pack(fill=tk.Y, expand=1)
return w
class App(tk.Tk):
"""Start here"""
def __init__(self):
super().__init__()
self.protocol("WM_DELETE_WINDOW", self.on_exit)
self.set_style()
self.set_title()
Main(self,)
def set_style(self):
self.style = ttk.Style()
#('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
self.style.theme_use("vista") #change to your liking :)
def set_title(self):
s = "{0}".format('Employee Time-Clock')
self.title(s)
self.destroy()
def on_exit(self):
window.destroy()
#self.destroy()
#sys.exit()
#"""Close all"""
#if messagebox.askokcancel( self.title(), "Do you want to quit?", parent=self):
# self.destroy()
if __name__ == '__main__':
app = App()
app.mainloop()
Your code is a giant mess, brah ;D. What I gather from your question is that you need some kind of table. What I gather from your code is the table should have cells comprised of Label and Entry. You also want an interface to create entries. Below is an example of all of that. I don't really see anything to explain. It's just a bunch of Frame, Label, Entry and Button. The only real action is in Table. All that action is, is mathematically figuring out where to put the next Item. This is all really basic stuff.
import tkinter as tk
from tkinter import ttk
#the entire bottom row of the app.
#has a dependency on self.master.table ~ not good OOP
class EntryManager(tk.Frame):
def __init__(self, master, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.grid_columnconfigure(5, weight=1)
font='Helvetica 10 bold'
tk.Label(self, text='Label', font=font, width=5).grid(row=0, column=0, padx=2)
lbl = tk.Entry(self, width=10, font=font)
lbl.grid(row=0, column=1, padx=2)
tk.Label(self, text='Entry', font=font, width=5).grid(row=0, column=2, padx=2)
ent = tk.Entry(self, width=25, font=font)
ent.grid(row=0, column=3, padx=2)
tk.Button(self, text='add', font=font, command=lambda: self.master.table.addItem(lbl.get(), ent.get())).grid(row=0, column=4, padx=2, sticky='w')
tk.Label(self, text='rows', font=font, width=4).grid(row=0, column=5, padx=2, sticky='e')
r = tk.Entry(self, width=4, font=font)
r.insert('end', self.master.table.rows)
r.grid(row=0, column=6, padx=2)
tk.Label(self, text='cols', font=font, width=4).grid(row=0, column=7, padx=2)
c = tk.Entry(self, width=4, font=font)
c.insert('end', self.master.table.cols)
c.grid(row=0, column=8, padx=2)
tk.Button(self, text='set', font=font, command=lambda: self.master.table.setDims(r.get(), c.get())).grid(row=0, column=9, padx=2, sticky='e')
#generic scrollable frame
class ScrollFrame(tk.Frame):
def __init__(self, master, row=0, column=0, scrollspeed=.02, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.grid(row=row, column=column, sticky='nswe')
self.scrollspeed = scrollspeed
self.canvas = tk.Canvas(self, highlightthickness=0)
self.canvas.grid(column=0, row=0, sticky='nswe')
self.v_scroll = tk.Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.v_scroll.grid(row=0, column=1, sticky='ns')
self.canvas.configure(yscrollcommand=self.v_scroll.set)
self.canvas.bind_all('<MouseWheel>', self.on_mousewheel)
self.frame = tk.Frame(self.canvas, height=0)
self.frame.grid_columnconfigure(0, weight=1)
self.frame.bind('<Configure>', lambda e:self.canvas.configure(scrollregion=self.canvas.bbox("all")))
self.canvas.create_window((0,0), window=self.frame, anchor="nw")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
def on_mousewheel(self, event):
self.canvas.yview_moveto(self.v_scroll.get()[0]+((-event.delta/abs(event.delta))*self.scrollspeed))
#a table cell
class Item(tk.Frame):
#property
def value(self):
return self.__value.get()
#value.setter
def value(self, text):
self.__value.set(text)
def __init__(self, master, text, value, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
tk.Label(self, text=text, width=10, font='none 8 bold').grid(row=0, column=0, pady=5, padx=5)
self.__value = tk.StringVar(value=value)
tk.Entry(self, textvariable=self.__value, width=25).grid(row=0, column=1, pady=5, padx=5)
#the table
class Table(ScrollFrame):
def __init__(self, master, rows=15, cols=3, **kwargs):
ScrollFrame.__init__(self, master, **kwargs)
self.entries = []
self.rows = rows
self.cols = cols
def addItem(self, text, value):
if len(self.entries) < self.rows*self.cols:
self.entries.append(Item(self.frame, text, value))
self.entries[-1].grid(row=(len(self.entries)-1)%self.rows, column=(len(self.entries)-1)//self.rows)
def getItem(self, row, column):
return self.entries[self.rows*column+row].value
def setDims(self, rows, cols):
if rows.isnumeric():
self.rows = int(rows)
if cols.isnumeric():
self.cols = int(cols)
for ent in self.entries:
ent.grid_forget()
for i, ent in enumerate(self.entries):
if i < self.rows*self.cols:
ent.grid(row=i%self.rows, column=i//self.rows)
class App(tk.Tk):
WIDTH, HEIGHT, TITLE = 770, 465, 'Application'
def __init__(self):
tk.Tk.__init__(self)
ttk.Style().theme_use("vista")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.table = Table(self, rows=20, cols=3)
self.table.grid(row=0, column=0, sticky='nswe')
EntryManager(self).grid(row=1, column=0, sticky='nswe', ipady=5)
#junk for testing
for i in range(12):
self.table.addItem(f'entry_{i}', f'data {i}')
if __name__ == '__main__':
app = App()
app.config(background='black')
app.title(App.TITLE)
app.geometry(f'{App.WIDTH}x{App.HEIGHT}')
#app.resizable(width=False, height=False)
app.mainloop()
Might as well dump the table keys in the table and see what happens. The sizes and alignments of things could use some work.

How to access individual Button tkinter?

Goal : dynamically create label and button (represents a task) and when I click this button it should destroy the label and button.
Problem : Unable to access buttons individually
Here is my code :
class Gui:
# constructor
def __init__(self, root):
self.root = root
self.root.title("TASKS")
self.root.geometry("300x700")
self.root.resizable(width=False, height=False)
self.clock = Label(self.root, fg="blue")
self.clock.grid(row = 0,column = 0,padx = 80,pady = 40)
self.update_clock()
self.new_button = Button(self.root, text="New",command = self.newwindow).grid(row = 0, column =1)
self.r =0
# clock
def update_clock(self):
now = strftime("%H:%M:%S")
self.clock.configure(text=now)
self.clock.after(1000, self.update_clock)
# label creator
def label(self, txt):
self.l = Label(self.root, text=txt, fg="red",pady =15)
self.l.grid(row = self.r, column =0)
# button creator
def donebutton(self):
self.b = Button(self.root, text="Done",command = lambda : self.del_task())
self.b.grid(row = self.r,column = 1)
# create a task
def task(self,txt):
self.r +=1
self.label(txt)
self.donebutton()
# delete task
def del_task(self):
self.l.destroy()
self.b.destroy()
# display gui method
def display(self):
self.root.mainloop()
# new window
def newwindow(self):
self.newwindow = Toplevel(self.root)
self.newwindow.title("NEW TASK")
self.newwindow.geometry("300x200")
self.newwindow.resizable(width=False, height=False)
Label(self.newwindow,text="Task").grid()
self.t1 = Text(self.newwindow,height = 2,width = 36)
self.t2 = Text(self.newwindow,height = 2,width = 10)
self.t1.grid()
Label(self.newwindow, text="Time").grid()
self.t2.grid()
self.c_b=Button(self.newwindow,text = "CREATE",command = lambda : self.task(self.t1.get("1.0",END)))
self.c_b.grid()
if __name__ == '__main__':
a = Gui(Tk())
a.display()
Requesting help with the code and I do not mind changing the whole code.
You keep overwriting the button. You said you don't care if the code is written completely different so, I changed a bunch.
Windows, Clock and Tasks are separated into classes
no targetable references to windows or buttons are held
the command for the "New Button" creates the NewTasks window
the command for the "Done Button" destroys its parent
the command for the "Create Button" creates a Task in the main window
a scrollable frame was added so tasks can never vertically overflow the main window
start, pause, done and remove Buttons were included
a scrollable output panel was included
ability to reposition tasks in the display is included
task labels can be clicked to show their content in the output panel
start, pause and done report to the output, and done includes elapsed time
once a task is started it cannot be removed
a task can only be "done" if it is running
a modicum of widget/grid formatting was applied to stop the display from jumping around as tasks were created/removed
I got bored and built your app ... probably.
from tkinter import Tk, Button, Label, Toplevel, Text, Frame, Canvas, Scrollbar
from time import strftime, time
class Task(Frame):
def __init__(self, master, text, output, move, **kwargs):
Frame.__init__(self, master, **kwargs)
self.grid_columnconfigure(0, weight=1)
self.stored = []
self.starttime = 0
self.send_output= output
self.lbl = Label(self, text=text, height=1, anchor='nw', fg='blue', font='calibri 14')
self.lbl.grid(row=0, column=0, sticky='nswe')
self.lbl.bind('<1>', self.output)
font = 'consolas 10 bold'
self.b1 = Button(self, font=font, text=chr(9654), command=self.start)
self.b2 = Button(self, font=font, text=chr(10073)+chr(10073), state='disabled', command=self.pause)
self.b3 = Button(self, font=font, text=chr(10006), state='disabled', command=self.done)
self.b4 = Button(self, font=font, text=chr(9866), command=self.destroy)
self.b5 = Button(self, font=font, text=chr(9650), command=lambda: move(self, -1))
self.b6 = Button(self, font=font, text=chr(9660), command=lambda: move(self, 1))
self.b1.grid(row=0, column=1) #start
self.b2.grid(row=0, column=2) #pause
self.b3.grid(row=0, column=3) #done
self.b4.grid(row=0, column=4) #remove
self.b5.grid(row=0, column=5) #move up
self.b6.grid(row=0, column=6) #move down
def start(self):
self.b1['state'] = 'disabled'
self.b2['state'] = 'normal'
self.b3['state'] = 'normal'
self.b4['state'] = 'disabled'
self.starttime = time()
self.send_output(f"{self.lbl['text']}", f"{strftime('%I:%M:%S')} STARTED: ")
def pause(self):
self.b1['state'] = 'normal'
self.b2['state'] = 'disabled'
self.b3['state'] = 'disabled'
self.stored.append(time() - self.starttime)
self.send_output(f"{self.lbl['text']}", f"{strftime('%I:%M:%S')} PAUSED: ")
def done(self):
self.stored.append(time() - self.starttime)
t = sum(self.stored)
self.send_output(f"{self.lbl['text']}\telapsed time: {self.etime(t)}\n", f"{strftime('%I:%M:%S')} FINISHED: ")
self.destroy()
def etime(self, s):
h = int(s//3600)
s -= 3600*h
m = int(s//60)
s -= 60*m
return f'{h:02}:{m:02}:{int(s):02}'
def output(self, event):
self.send_output(self.lbl['text'], 'Task: ')
class NewTasks(Toplevel):
WIDTH = 416
HEIGHT = 50
def __init__(self, master, slave, output, move, **kwargs):
Toplevel.__init__(self, master, **kwargs)
self.title("New Task")
self.geometry(f'{NewTasks.WIDTH}x{NewTasks.HEIGHT}')
self.resizable(width=False, height=False)
Label(self, text="Task").grid(row=0, column=0)
txt = Text(self, height=2, width=36, font='consolas 12')
txt.grid(row=0, column=1)
Button(self, text="CREATE", command=lambda: self.create(slave, output, move, txt)).grid(row=0, column=2, sticky='e', padx=4, pady=12)
def create(self, target, output, move, txt):
t = Task(target.frame, txt.get("1.0",'end'), output, move)
t.grid(column=0, sticky='nswe')
target.update(t)
class ScrollFrame(Canvas):
def __init__(self, master, **kwargs):
Canvas.__init__(self, master, **kwargs)
vsb = Scrollbar(self, orient='vertical', command=self.yview)
vsb.pack(side='right', fill='y')
self.configure(yscrollcommand=vsb.set)
self.frame = Frame(self, height=0)
self.frame.grid_columnconfigure(0, weight=1)
self.frame.bind('<Configure>', lambda e:self.configure(scrollregion=self.bbox("all")))
self.create_window((0,0), width=App.WIDTH-20, window=self.frame, anchor="nw")
self.movelist = []
def update(self, target):
self.movelist.append(target)
def move_item(self, elem, dir=1):
c = self.frame.winfo_children()
i = self.movelist.index(elem)
if i+dir in range(0, len(self.movelist)):
e = self.movelist.pop(i)
self.movelist.insert(i+dir, e)
for n in range(len(self.movelist)):
while n < len(self.movelist) and self.movelist[n] not in c:
self.movelist.pop(n)
if n < len(self.movelist):
self.movelist[n].grid(row=n, column=0, sticky='nswe')
continue
break
class Clock(Label):
def __init__(self, master, **kwargs):
Label.__init__(self, master, **kwargs)
self.update()
def update(self):
self['text'] = strftime('%I:%M:%S')
self.after(1000, self.update)
class App(Tk):
WIDTH = 600
HEIGHT = 447
def __init__(self, **kwargs):
Tk.__init__(self, **kwargs)
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(0, weight=1)
Clock(self, fg="blue", font='calibri 18').grid(row=0, column=0, ipady=10, sticky='nswe')
sf = ScrollFrame(self, highlightthickness=0)
sf.grid(row=1, column=0, columnspan=3, sticky='nswe')
command = lambda: NewTasks(self, sf, self.output, sf.move_item)
Button(self, text="New", font='calibri 12', command=command).grid(row=0, column=1, columnspan=2)
self.out = Text(self, height=8, font="calibri 14")
self.out.grid(row=2, column=0, columnspan=2)
self.out.tag_configure("bold", font="calibri 12 bold")
vsb = Scrollbar(self, orient='vertical', command=self.out.yview)
vsb.grid(row=2, column=2, sticky='ns')
self.out.configure(yscrollcommand=vsb.set)
def output(self, text, btext=''):
self.out.insert('end', btext, 'bold')
self.out.insert('end', text)
if __name__ == '__main__':
app = App()
app.title("Task Scheduler")
app.geometry(f'{App.WIDTH}x{App.HEIGHT}')
app.resizable(width=False, height=False)
app.mainloop()

Calling lists when lists when lists are empty in TKinter

I wish to print from a list where the user enters an input and then has that input printed from a list. This however doesn't work without a blank string in the list as it says that the list is too short for the data to be shown in a label. I want for this to have the input printed immediately after pressing the continue button not after pressing the next button.
from tkinter import *
class Traveller:
def __init__(self, parent):
self.names = [""]
self.E_phone = "f"
self.E_name = "q"
self.count = 0
self.go = Frame(parent, width=500, height=450, bg="snow", pady=30, padx=10)
self.go.grid(row=1, column=0)
self.go.grid_propagate(0) # to reserve space required for frame
self.dataView = Frame(parent, width=500, height=500, bg="snow", pady=30, padx=10)
name = Label(self.go, text="Name:", bg="snow")
name.grid(row=1, column=0, sticky=E)
self.E_name = Entry(self.go, width=40)
self.E_name.grid(row=1, column=1, sticky=W, pady=4)
menuButton = Button(self.go, text="Continue", command=self.dataSave)
menuButton.grid(row=2, column=1, pady=4)
dataTitle = Label(self.dataView, text="Here is all of the inputted data:", bg="snow")
dataTitle.grid(row=2, column=0)
dataExit = Button(self.dataView, text="Return", command=self.returnT)
dataExit.grid(row=1, column=0, pady=5)
nextData = Button(self.dataView, text="Next", command=self.NData)
nextData.grid(row=4, column=0, pady=5)
prevData = Button(self.dataView, text="Previous", command=self.PData)
prevData.grid(row=4, column=1, pady=5)
self.everything = Label(self.dataView, text="The person" + self.names[self.count], bg = "snow")
self.everything.grid(row=3, column = 0)
def dataSave(self):
self.names.append(self.E_name.get())
self.go.grid_remove()
self.dataView.grid(row=1, column=0)
self.dataView.grid_propagate(0)
# clearing the entry boxes
self.E_name.delete(0, END)
def returnT(self):
self.dataView.grid_remove()
self.go.grid(row=1, column=0)
self.go.grid_propagate(0)
def NData(self):
self.count = self.count + 1
self.everything.configure(text = "The person " + self.names[self.count])
def PData(self):
if self.count >= 1:
self.count = self.count - 1
self.everything.configure(text = "The person " + self.names[self.count])
# main routine
if __name__ == "__main__":
root = Tk()
root.title("Traveller Details")
play = Traveller(root)
root.geometry("500x450+0+0")
root.mainloop()

How do I remove a checkbutton when it is checked

I have built a simple to-do list and I am trying to get the checkbox to remove itself when it is checked(to signify that the task has been completed)
I am not sure how I need to be implementing the function in order to remove itself. Can anyone help me out with this. I've combed through a list of pages and none of them have really indicated how you do this.
class App(object):
def __init__(self, master):
self.master = master
self.frame = Frame(master)
self.frame.grid()
self.addFrame = Frame(master)
self.addFrame.grid(row=0, column=0, columnspan=2, sticky='N')
self.listFrame = Frame(master)
self.listFrame.grid(row=1, column=0, columnspan=2, sticky='NW')
self.todoList = []
self.initUI()
def initUI(self):
self.entryBox = Entry(self.frame, width = 15)
self.entryBox.grid(row=0, column=0, sticky='N')
self.addButton = Button(self.frame, text="<-ADD->", command=self.add)
self.addButton.grid(row=0, column=1, sticky='N')
def removeCheckButton(self):
# - CONFUSED HOW TO REMOVE THE SPECIFIC CHECKBUTTON
pass
def add(self):
entry = self.entryBox.get()
self.entryBox.delete(0, END)
self.todoList.append(entry)
print self.todoList
var1 = IntVar()
self.buttonList = []
for n in range(len(self.todoList)):
lx = Checkbutton(self.listFrame, text=self.todoList[n], variable=self.todoList[n], command=removeCheckButton)
lx.grid(row=n, column=0, sticky='NW')
self.buttonList.append(lx)
print self.buttonList
Have a look at this. your add is a bit strangely designed (and incorrectly IMO), so I modified it slightly as well as other parts.
from tkinter import *
class App(object):
def __init__(self, master):
self.master = master
self.frame = Frame(master)
self.frame.grid()
self.addFrame = Frame(master)
self.addFrame.grid(row=0, column=0, columnspan=2, sticky='N')
self.listFrame = Frame(master)
self.listFrame.grid(row=1, column=0, columnspan=2, sticky='NW')
self.todoList = []
self.buttonList = [] #<--- button list is here now
self.initUI()
def initUI(self):
self.entryBox = Entry(self.frame, width = 15)
self.entryBox.grid(row=0, column=0, sticky='N')
self.addButton = Button(self.frame, text="<-ADD->", command=self.add)
self.addButton.grid(row=0, column=1, sticky='N')
def removeCheckButton(self, button_no):
# - CONFUSED HOW TO REMOVE THE SPECIFIC CHECKBUTTON
# print(button_no, self.buttonList[button_no])
#self.buttonList[button_no].grid_forget()
self.buttonList[button_no].destroy()
# del self.buttonList[button_no]
# del self.todoList[button_no]
def add(self):
entry = self.entryBox.get()
self.entryBox.delete(0, END)
self.todoList.append(entry)
print(self.todoList)
var1 = IntVar()
#self.buttonList = [] #<--- not sense having this here
# for n in range(len(self.todoList)): #<-- this for also very strange here.
n = len(self.buttonList)
lx = Checkbutton(self.listFrame,
text=self.todoList[n],
variable=self.todoList[n],
command=lambda ni=n: self.removeCheckButton(ni))
lx.grid(row=n, column=0, sticky='NW')
self.buttonList.append(lx)
# print(self.buttonList)
root = Tk()
app = App(root)
root.mainloop()
P.S.
I use python 3, but except the import part, the code should execute for you. Probably it needs more fixing, but the checkboxes get destroyed now as they supposed to.

Categories

Resources