I'm trying to make a gui of a small project. I want to add the ability to once hitting add_item to add a data entry, it adds a time stamp to it as well. I'm very new to tkinter so any help would be great. I tried something like this:
tk.Button(root, text='add_item', command=lambda :text.insert("end", time.strftime("%d/%m/%Y%H:%M:%S")+'\n'))
b2.pack(side=tkinter.LEFT)
but couldn't get it to work with the rest of the code. I'm assuming it needs a lambda function, not sure how to set it up though.
import tkinter as tk
from datetime import datetime
import time
#1
now = datetime.now()
print ("Current date and time : ")
print (now.strftime("employee-attendance-list-%Y-%m-%d.csv"))
filename = datetime.now().strftime('employee-attendance-list-%Y-%m-%d.csv')
def dt_ins():
e.insert(0, time.asctime())
root = tk.Tk()
root.title("List App")
root.geometry("400x400")
def handler(e):
label= Label(win, text= "You Pressed Enter")
label.pack()
def retrievedata():
''' get data stored '''
global list_data
list_data = []
try:
with open (filename, "r", encoding="utf-8") as file:
for f in file:
listbox.insert(tk.END, f.strip())
list_data.append(f.strip())
print(list_data)
except:
pass
def reload_data():
listbox.delete(0, tk.END)
for d in list_data:
listbox.insert(0, d)
def add_item(event=1):
global list_data
if content.get() != "":
listbox.insert(tk.END, content.get())
list_data.append(content.get())
content.set("")
def delete():
global list_data
listbox.delete(0, tk.END)
list_data = []
def delete_selected():
try:
selected = listbox.get(listbox.curselection())
listbox.delete(listbox.curselection())
list_data.pop(list_data.index(selected))
# reload_data()
# # listbox.selection_clear(0, END)
listbox.selection_set(0)
listbox.activate(0)
listbox.event_generate("<<ListboxSelect>>")
print(listbox.curselection())
except:
pass
def quit():
global root
with open (filename, "w", encoding="utf-8") as file:
for d in list_data:
file.write(d + "\n")
root.destroy()
# LISTBOX
content = tk.StringVar()
entry = tk.Entry(root, textvariable=content)
entry.pack()
button = tk.Button(root, text="Add Item", command=lambda: [add_item(), dt_ins()])
button.pack()
entry.bind("<Return>", add_item)
button_delete = tk.Button(text="Delete", command=delete)
button_delete.pack()
button_delete_selected = tk.Button(text="Delete Selected", command=delete_selected)
button_delete_selected.pack()
listbox = tk.Listbox(root)
listbox.pack()
entry.bind("<Return>,", add_item)
bquit = tk.Button(root, text="Quit and save", command=quit)
bquit.pack()
retrievedata()
root.mainloop()
Related
im trying to name a button what it is named in ent and so it doesn't repeat when the button is pressed again so if you press once it's button1 and again button2
from tkinter import *
def ext():
win1.destroy()
but1 = Button(root, text=txt.get(), height=10, width=30)
but1.grid(padx=3, row=0, column=1)
def create():
global win1
global txt
win1 = Tk()
win1.geometry("200x200")
ent = Entry(win1)
ent.pack(pady=20)
txt = ent.get()
sub = Button(win1, text="Submit", command=ext)
sub.pack()
root = Tk()
root.geometry("750x750")
root.config(background="#6673ED")
create_but = Button(root, text="Create new card", height=10, width=30, command=create)
create_but.grid(row=0,column=0)
root.mainloop()
The code below uses a dictionary of lists to add an integer to any repeating text input. I think this is what the question is about.
import tkinter as tk # import as tk is safer and more flexible
# Globals to keep it simple
names = {} # Dictionary. Will become a dictionary of lists.
row = 1
col = 0
win1 = None
ent = None
def add_text( txt ):
""" Adds txt to the names dictionary if it doesn't already exist.
Adds and integer to the txt if it does already exit """
name = names.get( txt, None )
if name:
name.append( txt + str(len( name )) ) # Append `txt + int` to a list
else:
names[ txt ] = [ txt ] # Add a list of one item to the dict.
# print( names ) # Uncomment to see what is happening.
return names[ txt ][-1]
def ext():
global row, col
txt = ent.get() # Get the text from the entry
win1.destroy() # before the window is destroyed
txt = add_text( txt )
but1 = tk.Button(root, text=txt, height=10, width=30)
but1.grid(padx=3, row=row, column=col) # row and column need to
# change to show all buttons.
col += 1
if col > 2:
row += 1
col = 0
def create():
global win1
global ent
win1 = tk.Toplevel() # Create a second window with tk.Toplevel.
# Never create two tk.Tk objects.
win1.geometry("200x200")
ent = tk.Entry(win1)
ent.pack(pady=20)
ent.focus() # Position the focus in the Entry
# txt = ent.get() # removed as the Entry was being read before data was entered.
# The entry is now read in `ext`.
sub = tk.Button( win1, text="Submit", command=ext )
sub.pack()
root = tk.Tk()
root.geometry("750x750")
root.config(background="#6673ED")
create_but = tk.Button(root, text="Create new card", height=10, width=30, command=create)
create_but.grid(row=0,column=0)
root.mainloop()
Hello currently I'm working on a word occurrence counter, I created a gui for it where users can type the words and then press the "count" button and it will count the occurence of each word, however I want to make it so user can instead upload a text file and the word occurrence will count the occurence of each word in the text file instead. Does anyone know how to make the transition? I need to know how to change it from user input words to user upload text files.
import tkinter as tk
from tkinter import *
from collections import Counter
#Functions
def countWords(s):
signos = [',', '.', ';', ':']
cleanstr = ''
for letra in s.lower():
if letra in signos:
cleanstr += ''
else:
cleanstr += letra
strlist = cleanstr.split(' ')
return dict(Counter(strlist))
def button_count():
text = mainWindow.e2.get()
count = countWords(text)
myLabel = Label(root, text=count)
myLabel.pack()
#Graphics
root = tk.Tk()
root.title("Count words")
root.geometry('400x400')
#Background Image Label
bg = PhotoImage(file = "./guibackground.gif")
# Show image using label
label1 = Label( root, image = bg)
label1.place(relx=0.5, rely=0.5, anchor=CENTER)
#Class Window
class Window:
def __init__(self, root):
self.root = root
self.e2 = tk.StringVar()
self.e = tk.Entry(root, textvariable=self.e2, width=35, borderwidth=5)
self.e.pack()
self.button = Button(root, text="Count words", command=button_count)
self.button.pack()
self.exit_button = Button(root, text="Exit", command=root.quit)
self.exit_button.pack()
if __name__ == '__main__':
mainWindow = Window(root)
Use filedialog.askopenfilename method:
import tkinter as tk
from tkinter import filedialog
from collections import Counter
class App(object):
def __init__(self):
self.root = tk.Tk()
self.btn = tk.Button(text='Open File', command=self.open_file)
self.btn.pack()
self.lbl = tk.Label()
self.lbl.pack()
self.root.mainloop()
def open_file(self):
filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('text files','*.txt'), ('all files','*.*')))
with open(filename, 'r') as f:
self.lbl.configure(text=f'{Counter(f.read().split())}')
App()
Output:
what I want to do, is to open from the root window a toplevel window in which I have series of entry widgets, modify the entries and close the window. I found a code in one of the posts and modified it to fit my need. The code works only the first time I open the toplevel window, but after that it opens the toplevel window without the entry fields! I don't understand what is happening!! Can anyone help please? I am quite new to python. Here is the code:
from tkinter import *
root = Tk()
entry_list = []
def openwindow():
window = Toplevel()
window.title("Data")
entry_list.clear()
for i in range(10):
entry_list.append(Entry(window))
entry_list[i].grid()
def update_entry_fields():
for i in entry_list:
i.delete(END)
i.insert(0, "")
print(float(entry_list[0].get()))
def closewindow():
window.withdraw()
savebtn = Button(window, text="Save & print", command = update_entry_fields)
closebtn = Button(window, text="Close", command=closewindow)
savebtn.grid()
closebtn.grid()
def printout():
print(float(entry_list[0].get()))
printbtn = Button(root, text="Test print", command = printout)
printbtn.grid()
openbutton = Button(root, text="open data sheet", command=openwindow)
openbutton.grid()
root.mainloop()
Here is the solution that at least i was looking for.
from tkinter import *
root = Tk()
entry_list = []
p = [5, 6, 7, 8, 9]
def openwindow():
window = Toplevel()
window.title("Data")
entry_list.clear()
for i in range(5):
v = DoubleVar()
entry_list.append(Entry(window, textvariable=v))
entry_list[i].grid()
v.set(p[i]) # set default entry values
def update_entry_fields():
for i in range(5):
p[i]=entry_list[i].get() # overwrite the entry
# test print from inside
print(p[i])
window.withdraw()
savebtn = Button(window, text="Save & close", command = update_entry_fields)
savebtn.grid()
window.mainloop()
# Test print from outside of function
def printout():
print(p[0])
printbtn = Button(root, text="Test print", command = printout)
printbtn.grid()
openbutton = Button(root, text="open data sheet", command=openwindow)
openbutton.grid()
#
root.mainloop()
from tkinter import *
import sys,math,random,datetime,os,time
import tkinter.messagebox
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from time import gmtime, strftime
import xlsxwriter
export = "Excel"
current_time = strftime("%m-%d-%Y %H:%M", gmtime())
root = Tk()
e1 = Entry()
e1.insert(10, "First Name")
e2 = Entry()
e2.insert(10, "Last Name")
Here is where I am trying to format variable to become string.
fullname = "%s %s" % (e1, e2)
title = ["Titan Tech", "Caleb Fahlgren made this!", "Python is life!", "FIRST Robotics!","Doesn't this make your life easier?"]
title = (random.choice(title))
root.title(title)
root.geometry("640x600")
#Submit Button
def Submit():
submit = tkinter.messagebox.askquestion("Submit Entry", "Are you sure you want to submit?")
if submit == "yes":
Xlsx program.
workbook = xlsxwriter.Workbook('TitanTechSummary.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
worksheet.write('A1', 'Name:',bold)
This is where I am trying to write the players input for name. Or the tkinter Entry(). But I keep getting like a weird decimal number when I look at the excel document. I keep getting this in the B1 field '.140041879004720 .140041884602944'
worksheet.write_string('B1',fullname, bold)
worksheet.write('C1', 'Date:',bold)
I also want to do the same thing with the date.
worksheet.write('D1', 'Date')
workbook.close()
userconfirm = tkinter.messagebox.showinfo("Save","Your entry has been saved to an " + export + " document!")
def keypress(event):
if event.keysym == 'Escape':
root.destroy()
def Quit():
quitask = tkinter.messagebox.askquestion("Quit", "Are you sure you want to quit?")
if quitask == "yes":
root.destroy()
def Insert():
filen = askopenfilename()
filen1 = tkinter.messagebox.showinfo("Saved", "If you opened a picture we saved it!")
firstname = Label(root, text="First Name",font=("Helvetica", 12),fg="green")
lastname = Label(root, text="Last Name",font=("Helvetica", 12),fg="green")
time = Label(root, text=current_time, font=("Helvetica", 12),fg="black")
TextArea = Text()
ScrollBar = Scrollbar(root)
ScrollBar.config(command=TextArea.yview)
TextArea.config(yscrollcommand=ScrollBar.set)
ScrollBar.pack(side=RIGHT, fill=Y)
Submit = Button(root, fg="white", bg="green", text="Submit", width=50, command=Submit, activebackground="yellow")
Quit = Button(root, fg="white", bg="green", text="Quit", width=50, command=Quit,activebackground="yellow")
Insert = Button(root,fg="white", bg="green", text="Insert Images", width=50, command=Insert,activebackground="yellow")
root.bind_all('<Key>', keypress)
firstname.pack()
e1.pack()
lastname.pack()
e2.pack()
time.pack()
TextArea.pack(expand=YES, fill=BOTH)
Insert.pack()
Submit.pack()
Quit.pack()
mainloop()
The problem is this line of code:
fullname = "%s %s" % (e1, e2)
e1 and e2 are entry widgets. Their string representation (ie: if you do str(e1)) is going to be "a weird decimal number".
You need to be calling the get() method of the widget to get the contents:
fullname = "%s %s" % (e1.get(), e2.get())
I'm trying to put old school sequential Tkinter code into class structure code.
So let's consider this example :
import Tkinter as Tk
def StartProcess():
print Text_1_Var.get(), Text_2_Var.get(), Text_3_Var.get()
if __name__ == '__main__':
MainFrame = Tk.Tk()
Tk.Button(MainFrame , text = "Start",command=StartProcess).grid(column=2, row=0)
Tk.Label(MainFrame , text = "1").grid(column=1, row=1)
Text_1_Var = Tk.StringVar()
Text_1 = Tk.Entry(MainFrame , width=40, textvariable = Text_1_Var).grid(column=2, row=1)
Tk.Label(MainFrame , text = "2").grid(column=1, row=2)
Text_2_Var = Tk.StringVar()
Text_2 = Tk.Entry(MainFrame , width=40, textvariable = Text_2_Var).grid(column=2, row=2)
Tk.Label(MainFrame , text = "3").grid(column=1, row=3)
Text_3_Var = Tk.StringVar()
Text_3 = Tk.Entry(MainFrame , width=40, textvariable = Text_3_Var).grid(column=2, row=3)
# etc
MainFrame.mainloop()
On press "Start" it displays values of Entry from 1 to 3.
Now i recode it as follow :
import Tkinter as Tk
def StartProcess():
print "???"
class NewEntry(Tk.Frame):
def __init__(self,master=None,idnumber=None):
Tk.Frame.__init__(self,master)
self.pack(side=Tk.TOP)
self.CreateWidgets(idnumber)
def CreateWidgets(self,idnumber):
Tk.Label(master=self, text = idnumber).grid(column=1, row=0)
self.Text_Var = Tk.StringVar()
self.Text = Tk.Entry(master=self, width=40, textvariable = self.Text_Var).grid(column=2, row=0)
if __name__ == '__main__':
MainFrame = Tk.Tk()
Tk.Button(master=MainFrame,text="Start", command=StartProcess).pack()
for i in range (1, 4): # or more
NewEntry(master=MainFrame,idnumber=str(i))
MainFrame.mainloop()
GUI are both identical. I want to get the same result but i don't know where my function StartProcess should take place and how extract value of each self.Text_Var instance.
It's not enough to create a NewEntry object; you need to save references to them so you can access them later (e.g., from StartProcess).
entries = []
for i in range (1, 4): # or more
e = NewEntry(master=MainFrame,idnumber=str(i))
entries.append(e)
# Or more simply,
# entries = [NewEntry(master=MainFrame, idnumber=str(i)) for i in range(1,4)]
Then, StartProcess becomes something like
def StartProcess():
strings = [x.Text_Var.get() for x in entries]
print " ".join(strings)