You could use inputVal = input.get()
directly in delete_to_do()
without any global
and it would work.
But all this code has one big mistake. It gets current value from input
so button X
deletes wrong object on list - it doesn't delete value which is displayed with this button.
Other problem is that variable frame
can keep only last created frame
and button X
can remove only last frame and it can do it only once - so next X
may raise error. It would need to keep all frame
on list and search which frame to remove - similar to values on todo_list
.
But it would be much simpler to use lambda
to send value
and frame
directly to function delete_to_do()
.
command=lambda:delete_to_do(value, frame)
and later do
def delete_todo(value, frame):
todo_list.remove(value)
frame.destroy() # remove from memory because I will NO use it again
print(todo_list)
Of course this still have some problem: if you add the same element two times then second button will remove first item from list. It would need to keep data as dictionary with unique ID
and remove items using this unique ID
.
My version with many changes - but still without using unique IDs
import tkinter as tk # PEP8 `import *` is not proferred
# --- functions --- # PEP8: all functions before main code
def delete_todo(value, frame):
todo_list.remove(value) # it removes first matchin value - so it can remove wrong item
frame.destroy() # remove from memory because I will NO use it again
print(todo_list)
def update_list(value):
frame = tk.Frame(root)
frame.pack()
lbl = tk.Label(frame, text=value) # PEP8: inside `()` use `=` without spaces
lbl.pack(side="left")
btn = tk.Button(frame, text="x", command=lambda:delete_todo(value, frame)) # PEP8: inside `()` use `=` without spaces
btn.pack(side="right")
def add_input():
global y_axis # PEP8: space after globals
#global todo_list # you don't need `global` if you don't use `=` to assign new value
input_val = input.get()
todo_list.append(input_val)
y_axis += 35
print(todo_list)
update_list(input_val)
# --- main ---
todo_list = [] # PEP8: `lower_case_names` for variables
y_axis = 130 # PEP8: `lower_case_names` for variables
root = tk.Tk()
root.title("To Do")
root.geometry("500x700")
title = tk.Label(root, text="To Do", font=("Comic Sans", 45)) # PEP8: inside `()` use `=` without spaces
title.pack()
input = tk.Entry(root) # there is function `input()` and it would be better to use different variable (but I skip this problem)
input.pack()
add_button = tk.Button(root, text="Add", command=add_input) # PEP8: inside `()` use `=` without spaces
add_button.pack()
root.mainloop()
PEP 8 -- Style Guide for Python Code