Python tkinter xlsxwriter trying to export user input to excel file - python

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())

Related

adding date to tkinter data entry

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()

How do I get the Value of Tkcalendar/Date Entry

hi I am building a GUI where it should be possible to insert your name and your brthday that get´s stored in a sqllite3 database.
I use the Tkcalendar module to let the person choose it´s birthday.
My problem is I don´t know how to read out the Date.
I hope somebody can help me!
import sqlite3
verbindung = sqlite3.connect("Datenbanken/geb3.db")
zeiger = verbindung.cursor()
zeiger.execute("""CREATE TABLE IF NOT EXISTS people3(vorname VARCHAR(20), nachname VARCHAR(30), geburtstag DATE );""")
from tkinter import *
from tkcalendar import Calendar, DateEntry
root = Tk()
def speichern():
zeiger.execute("""INSERT INTO people3 VALUES (?,?,?) """, (eingabefeldvorname.get(), eingabefeldnachname.get(), eingabefelddatum.get()))
Label(root, text = "vorname").pack()
eingabefeldvorname=StringVar()
eingabefeld = Entry(root, textvariable = eingabefeldvorname, bg ="red").pack()
Label(root, text = "nachname").pack()
eingabefeldnachname = StringVar()
eingabefeld = Entry(root, textvariable = eingabefeldnachname, bg ="green").pack()
Label(root, text = "Geburtsdatum")
eingabefelddatum= DateEntry(root, width = 20, textvariable = eingabefelddatum, bg ="yellow").pack()
konpf2 = Button(root, text = "speichern", command = speichern).pack()
root.mainloop()
zeiger.execute("SELECT * FROM people3")
inhalt = zeiger.fetchall()
print(inhalt)
def listeleeren():
zeiger.execute("DELETE FROM people3")
listeleeren()
verbindung.commit()
verbindung.close()```
To get the value of DataEntry, the fuction get_date() works.
Reference: https://pypi.org/project/tkcalendar/#dateentry-widget
also you can use a <<DateEntrySelected>> event which is generated each time the user selects a date with the mouse.
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
def dateentry_view():
def print_sel(e):
print(cal.get_date())
top = tk.Toplevel(root)
ttk.Label(top, text='Choose date').pack(padx=10, pady=10)
cal = DateEntry(top, width=12, background='darkblue',
foreground='white', borderwidth=2)
cal.pack(padx=10, pady=10)
cal.bind("<<DateEntrySelected>>", print_sel)
root = tk.Tk()
ttk.Button(root, text='DateEntry', command=dateentry_view).pack(padx=10, pady=10)
root.mainloop()

get entered text and exit if the text in mass (tkinter)

good day! here's my code:
import tkinter as tk
namemass =["dev", "Dev1"]
self.entry_name = ttk.Entry(self)
self.entry_name.place(x=200, y=50)
btn_cancel = ttk.Button(self, text="cancel", command=self.destroy)
btn_cancel.place(x=300, y=800)
btn_ok = ttk.Button(self, text="ok")
btn_ok.place(x=320, y=170)
so, i have 2 buttons and enter box. I want the program to get the text from the enter box and if namemass list have that inside, then exit. in console program i would code it like that:
name = input()
namemass = ["dev", "Dev1"]
if name in namemass:
import sys
sys.exit()
else:
..........
how to do it using tkinter? thank you in advance!
To fetch the current entry text, use the get method:
current_text = Entry.get()
in your example you can just:
from tkinter import *
import sys
def destroy():
name = entry_name.get()
if name in namemass:
sys.exit()
root = Tk()
namemass = ["dev", "Dev1"]
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok")
btn_ok.pack()
root.mainloop()
Much easier for Python 3.8, using Walrus. Just add the function for _ok. And add command in btn_ok.
from tkinter import *
import sys
namemass = ["dev", "Dev1"]
def destroy():
#sys.exit()
root.destroy()
def _ok():
if(name_in_list := entry_name.get()) in namemass:
sys.exit()
root = Tk()
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok", command=_ok)
btn_ok.pack()
root.mainloop()

I cant generate a random number and print it

I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()

Need to display \r\n in entry box Python Tkinter

I have a program where i need to display in an entry box the \r\n characters. However in this entry box in tkinter they don't show up. When I send and return over serial, the \r\n shows up on what is returned so the characters are there, they're just not being displayed.
Is there any way to get these characters to show up in the entry box without having to manually enter them each time.
Here is the code
from tkinter import *
title_str = "Entry Boxes Test"
root = Tk()
root.title(title_str)
f1_value = StringVar()
f1_value.set("=> HELP\r\n")
f2_value = StringVar()
f2_value.set("=> VERSION\r\n")
def callback_f1():
listbox.insert(END, f1_entry.get())
listbox.see(END)
return
def callback_f2():
listbox.insert(END, f2_entry.get())
listbox.see(END)
return
title_frame = Frame(root)
title_frame.pack(side=TOP)
body_frame = Frame(root)
body_frame.pack(side=TOP)
left = Frame(body_frame)
right = Frame(body_frame)
left.pack(side=LEFT)
right.pack(side=LEFT)
bottom_frame = Frame(root)
bottom_frame.pack(side=TOP)
#attach scroll bar to bottom frame for messages
scrollbar = Scrollbar(bottom_frame)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(bottom_frame, width=40)
listbox.pack()
# attach listbox to scrollbar
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
title_var = StringVar()
title = Label(title_frame, textvariable=title_var, relief=FLAT, height=2)
title_var.set(title_str)
title.pack(side=TOP)
#F1 and F2
f1_button = Button(left, text="F1", width=15, height=2, command=callback_f1, state=NORMAL)
f1_button.pack(side=TOP)
f1_entry = Entry(left, textvariable=f1_value, width=18)
f1_entry.pack(side=TOP)
f2_button = Button(right, text="F2", width=15, height=2, command=callback_f2, state=NORMAL)
f2_button.pack(side=TOP)
f2_entry = Entry(right, textvariable=f2_value, width=18)
f2_entry.pack(side=TOP)
root.mainloop()
I've tried separating it like
f1_value.set("=> Help" + "\r\n")
and
f1_value.set("=> FUP{ret}".format(ret="\r\n"))
but nothings worked so far.
Thanks in advance!
Sending this over serial,
ser = serial.Serial()
def write_ser(st):
ser.write(st.encode())
time.sleep(1)
while ser.inWaiting():
try:
s = ser.read(20)
except:
listbox.insert(END, "read failed")
listbox.see(END)
return
listbox.insert(END, "<" + str(s)[2:-1] + ">")
listbox.see(END)
return
with, e.g. for f1,
def callback_f1():
listbox.insert(END, f1_entry.get())
listbox.see(END)
write_ser(f1_entry.get())
return
If you mean to display \ literally, escape them:
f1_value = StringVar()
f1_value.set("=> HELP\\r\\n")
f2_value = StringVar()
f2_value.set("=> VERSION\\r\\n")
or use r'raw string literals':
f1_value = StringVar()
f1_value.set(r"=> HELP\r\n")
f2_value = StringVar()
f2_value.set(r"=> VERSION\r\n")

Categories