I am trying to let the user add three entries and the code will use them to get data from an API and then export the data to CSV. I am trying to do it like this but I am not sure what is the issue and I am still new on Tkinter.
from Tkinter import *
import sys
import csv
from urllib import urlopen
import json
from dateutil.relativedelta import relativedelta
from datetime import datetime
import pandas as pd
root = Tk()
start2 = StringVar()
end2 = StringVar()
root.geometry("1600x800+0+0")
root.title("Data")
startd = "2017-13-03"
endd = "2017-13-03"
power1 =""
ID = "1232.4343.323"
class data1:
def __init__(self,master):
frame = Frame(master)
#frame.pack()
Tops = Frame(root, width=1600, height=1000, bg="powder blue")
Tops.pack(side=TOP)
self.output()
thelabel = Label(Tops, text="Data",font =('arial',30))
thelabel.pack(side=TOP)
def output(self):
Label(text='Start Date:',font=('arial', 12, 'bold')).pack(side=LEFT,padx=12,pady=12)
self.startd = Entry(root, width=10)
self.startd.pack(side=LEFT,padx=2,pady=16)
Label(text='End Date:',font=('arial', 12, 'bold')).pack(side=LEFT,padx=12,pady=12)
self.endd = Entry(root, width=10)
self.endd.pack(side=LEFT,padx=2,pady=16)
Label(text='Device ID:',font=('arial', 12, 'bold')).pack(side=LEFT,padx=12,pady=12)
self.ID = Entry(root, width=10)
self.ID.pack(side=LEFT,padx=2,pady=16)
self.b = Button(root, text='Submit', command=self.getjsondata)
self.b.pack(side=LEFT,padx=20,pady=5)
def getjsondata(self):
global power1
url1 = "https://api.data.com/mongo/measures/"+ID+"/"+startd+"/"+endd+"/?format=json"
power1 = urlopen(url1).read()
power1 = json.loads(power1)
power11 = pd.DataFrame(power1)
power11.csv(power11, file="MyData.csv")
b = data1(root)
root.mainloop()
The data comes in a json format and this is how the data comes:
[{"timestamp":"2017-01-14T19:47:00Z","value":"423"},{"timestamp":"2017-01-14T19:47:30Z","value":"419"},{"timestamp":"2017-01-14T19:48:00Z","value":"431"},{"timestamp":"2017-01-14T19:48:30Z","value":"429"},{"timestamp":"2017-01-14T19:49:00Z","value":"422"},{"timestamp":"2017-01-14T19:49:30Z","value":"427"},{"timestamp":"2017-01-14T19:50:00Z","value":"426"},{"timestamp":"2017-01-14T19:50:30Z","value":"427"},{"timestamp":"2017-01-14T19:51:00Z","value":"428"},{"timestamp":"2017-01-14T19:51:30Z","value":"426"},{"timestamp":"2017-01-14T19:52:00Z","value":"424"},{"timestamp":"2017-01-14T19:52:30Z","value":"423"},{"timestamp":"2017-01-14T19:53:00Z","value":"453"},{"timestamp":"2017-01-14T19:53:30Z","value":"433"},{"timestamp":"2017-01-14T19:54:00Z","value":"445"},{"timestamp":"2017-01-14T19:54:30Z","value":"438"},{"timestamp":"2017-01-14T19:55:00Z","value":"430"},{"timestamp":"2017-01-14T19:55:30Z","value":"437"},{"timestamp":"2017-01-14T19:56:00Z","value":"425"},{"timestamp":"2017-01-14T19:56:30Z","value":"420"},{"timestamp":"2017-01-14T19:57:00Z","value":"431"},{"timestamp":"2017-01-14T19:57:30Z","value":"435"},{"timestamp":"2017-01-14T19:58:00Z","value":"443"},{"timestamp":"2017-01-14T19:58:30Z","value":"430"},{"timestamp":"2017-01-14T19:59:00Z","value":"425"},{"timestamp":"2017-01-14T19:59:30Z","value":"406"},{"timestamp":"2017-01-14T20:00:00Z","value":"412"},{"timestamp":"2017-01-14T20:00:30Z","value":"417"},{"timestamp":"2017-01-14T20:01:00Z","value":"422"},{"timestamp":"2017-01-14T20:01:30Z","value":"422"},{"timestamp":"2017-01-14T20:02:00Z","value":"418"},{"timestamp":"2017-01-14T20:02:30Z","value":"415"},{"timestamp":"2017-01-14T20:03:00Z","value":"423"},{"timestamp":"2017-01-14T20:03:30Z","value":"411"},{"timestamp":"2017-01-14T20:04:00Z","value":"413"}]
I have filtered the data using panadas, my main issue is how to link an entry to a variable that I could use in my code. The entries are:
ID:
Starting date:
Ending date:
Please let me know what is the issue in my code.On the other hand I am planing to give the user the open in where to save the csv file on his computer if that is possible.
Thanks in advance
If problem is on pandas side:
It seems you need read_json and then if need select data by timestamps use loc:
df = pd.read_json(url1).set_index('timestamp')
print (df)
value
timestamp
2017-01-14 19:47:00 423
2017-01-14 19:47:30 419
2017-01-14 19:48:00 431
2017-01-14 19:48:30 429
...
...
date = pd.to_datetime('2017-01-14 19:47:00')
var = df.loc[date, 'value']
print (var)
423
Related
I'm aware that my code isn't very clean, , my primary focus at the moment is to make the program work.
I’m working with Tkinter and I created a search- and listbox based on a column in Excel. The Excelfile is imported by pandas, as a dataframe. The idea is that people can search for something (for example ‘Eiffel Tower’), that the value (‘Eiffel Tower’) is selected and that Python gives the construction date as output (so for example the year 1889) in the interface.
You search and make sure that the value is visible in the entrybox, and then you click on a button. After clicking on the button, you will see ‘1889’.
Both the buildings as the construction dates are listed in an Excelfile. Column A contains the buildings, column B contains the construction dates.
The search and listbox works. But I’m not ably to connect column A to column B, or to get an output based on the input that the uses gives.
The 'output_Startdate' was to test if the if-statement worked (what it does). The 'def connectie()' is me trying to find a solution.
My code:
import tkinter as tk
from tkinter import *
from tkinter import Listbox
from tkinter import ttk
import pandas as pd
interface = tk.Tk()
interface.configure(bg="#60c1c9")
interface.geometry('1500x750')
interface.title('Construction Dates')
title = Label(interface, text='1. BUILDINGS')
title.configure(bg="#60c1c9", fg="#000000", font=("Calibri", 20, "bold"))
title.place(relx=0.15, rely=0, anchor=N)
file_name = “List_Buildings.xlsx”
xl_workbook = pd.ExcelFile(file_name)
df = xl_workbook.parse(“Buildings”)
alist = df['MONUMENT'].tolist()
Startdate = df['Startdate'].tolist()
Enddate = df['Enddate'].tolist()
Label(
text="Select what you see on the picture.",
bg="#60c1c9",
fg="#000000",
font=("Calibri", 12)
).place(relx=0.29, rely=0.05, anchor=N)
def update(data):
my_list_1.delete(0, END)
for entry in data:
my_list_1.insert(END, entry)
def check(e):
typed = entry_1.get()
if typed == '':
data = alist
else:
data = []
for item in alist:
if typed.lower() in item.lower():
data.append(item)
update(data)
def fillout(e):
entry_1.delete(0, END)
entry_1.insert(0, my_list_1.get(ACTIVE))
entry_1 = Entry(interface, width=53)
entry_1.place(relx=0.205, rely=0.12, anchor=N)
entry_1.bind('<KeyRelease>', check)
my_list_1: Listbox = Listbox(interface, height=20, width=50)
my_list_1.place(relx=0.2, rely=0.15, anchor=N)
my_list_1.bind("<<ListboxSelect>>", fillout)
scrollbar_v = Scrollbar(interface, orient=VERTICAL, command=my_list_1.yview)
scrollbar_v.place(relx=0.301, rely=0.151, height=324)
scrollbar_h = Scrollbar(interface, orient=HORIZONTAL, command=my_list_1.xview)
scrollbar_h.place(relx=0.0985, rely=0.583, width=320.5)
#alist = df['MONUMENT'].tolist()
#output = df['Startdate'].tolist()
#df2 = pd.DataFrame(columns=['MONUMENT', 'Startdate', 'Enddate'])
#df2 = df.apply(lambda x: df['MONUMENT'] == df['Startdate'])
#print(df2)
def connectie():
value = entry_1.get()
for i in df['MONUMENT']:
if value == alist:
BLOCK_NAME.set(output)
return
def output_Startdate():
if entry_1.get() == ‘Eiffeltower’:
tekst = tk.Label(interface, text="good")
tekst.place(relx=0.3, rely=0.8)
else:
tekst = tk.Label(interface, text="this value doesn't excist")
tekst.place(relx=0.3, rely=0.8)
button = Button(interface, text='click here', command=output_Startdate)
button.place(relx=0.29, rely=0.7)
interface.mainloop()
I'm not sure what your data looks like (you didn't hand us a sample), so I hope I did it right. There are two parts to my answer, the first is for loading the file and setting the index column (I hope the names are all unique), and the second part is how to loc for the data you are looking for.
file_name = 'List_Buildings.xlsx' # file name
# read the file's Sheet1 and create dataframe with column 'MONUMENT' as index
df = pd.read_excel(file_name, 'Sheet1', index_col='MONUMENT')
# create alist from the index
alist = df.index.tolist()
def output_Startdate():
# get the entry_1 value
monument = entry_1.get()
# use monument (the entry_1 value) as index for dataframe loc and 'Startdate' as the column
start_date = df.loc[monument, 'Startdate']
# set the text for the label
tekst = tk.Label(interface, text=f"Start date: {start_date}")
tekst.place(relx=0.3, rely=0.8)
I am a newbie at Tkinter. I try this project, but I want to save the table as data frame because I want to process it more.
from tkinter import * from tkinter import ttk
ws=Tk()
ws.title('PythonGuides') ws.geometry('500x500')
set = ttk.Treeview(ws) set.pack()
set['columns']= ('id', 'full_Name','award') set.column("#0", width=0, stretch=NO) set.column("id",anchor=CENTER, width=80) set.column("full_Name",anchor=CENTER, width=80) set.column("award",anchor=CENTER, width=80)
set.heading("#0",text="",anchor=CENTER) set.heading("id",text="ID",anchor=CENTER) set.heading("full_Name",text="Full_Name",anchor=CENTER) set.heading("award",text="Award",anchor=CENTER)
global count count=0
for record in data:
set.insert(parent='',index='end',iid = count,text='',values=(record[0],record[1],record[2]))
count += 1
Input_frame = Frame(ws) Input_frame.pack()
id = Label(Input_frame,text="ID") id.grid(row=0,column=0)
full_Name= Label(Input_frame,text="Full_Name") full_Name.grid(row=0,column=1)
award = Label(Input_frame,text="Award") award.grid(row=0,column=2)
id_entry = Entry(Input_frame) id_entry.grid(row=1,column=0)
fullname_entry = Entry(Input_frame) fullname_entry.grid(row=1,column=1)
award_entry = Entry(Input_frame) award_entry.grid(row=1,column=2)
def input_record():
global count
set.insert(parent='',index='end',iid = count,text='',values=(id_entry.get(),fullname_entry.get(),award_entry.get()))
count += 1
id_entry.delete(0,END)
fullname_entry.delete(0,END)
award_entry.delete(0,END)
#button Input_button = Button(ws,text = "Input Record",command= input_record)
Input_button.pack()
ws.mainloop()
I plan to use it as inputs to do TOPSIS. Here is the reference for the TOPSIS.
Thanks before.
import pandas as pd
df = pd.DataFrame([value for value in [my_game.item(line)['values'] for line in my_game.get_children()]],
columns=my_game['columns'])
I am trying to make a weather forecast "app" using python, following the instructions of this video: https://www.youtube.com/watch?v=7JoMTQgdxg0
Everything works fine, except from the functionality of displaying some icons to make it look better.
If i remove the code that its used for the icons, everything works perfect. I don´t know what I should do so this works.
from tkinter import *
from tkinter import messagebox
from configparser import ConfigParser
import requests
url = "https://api.openweathermap.org/data/2.5/weather?q={}&appid={}"
config_file = 'config.ini'
config = ConfigParser()
config.read(config_file)
api_key = config['api_key']['key']
def get_weather(city):
result = requests.get(url.format(city, api_key))
if result:
#print(result.content)
json = result.json()
#City, country, temp_celsius, temp:farenheit, icon weather
city = json['name']
country = json['sys']['country']
temp_kelvin = json['main']['temp']
temp_celsius = temp_kelvin - 273.15
temp_farenheit = (temp_kelvin - 273.15) * 9 / 5 + 32
icon = json['weather'][0]['icon']
weather = json['weather'][0]['main']
final = (city, country, temp_celsius, temp_farenheit, icon, weather)
return final
else:
return None
#print(get_weather('London'))
def search():
city = city_text.get()
weather = get_weather(city)
if weather:
location_lbl['text'] = '{}, {}'.format(weather[0], weather[1])
image['bitmap'] = 'weather_icons/{}.png'.format(weather[4])#HERE ITS THE PROBLEM
temp_lbl['text'] = '{:.2f}ºC, {:.2f}ºF'.format(weather[2], weather[3])
weather_lbl['text'] = weather[5]
else:
messagebox.showerror('Error', 'Cannot find city {}'.format(city))
app = Tk()
app.title("Weather App")
app.geometry('700x350')
city_text = StringVar()
city_entry = Entry(app, textvariable=city_text)
city_entry.pack()
search_btn = Button(app, text='Search Weather', width=12, command=search)
search_btn.pack()
location_lbl = Label(app, text="", font=('bold', 20))
location_lbl.pack()
image = Label(app, bitmap='')#HERE ITS THE PROBLEM
image.pack()
temp_lbl = Label(app, text="")
temp_lbl.pack()
weather_lbl = Label(app, text="")
weather_lbl.pack()
app.mainloop()
I also have another file that its called: config.ini for saving my API key, and a folder named weather_icons for storing the images
.
def Verification():
date_format = "%d/%m/%Y"
if (datetime.strptime("1/1/2001", date_format) <= date_ < datetime.strptime("31/1/2008", date_format)):
print('bravo')
date_= datetime.strptime(date_,date_format)
vt=date_
vt =StringVar()
vt.set('')
lb = Label(parent, text = 'birth day: ')
cp = Entry(parent, textvariable=vt)
bt = Button(parent, text ='Verify', command = Verification)
lb.place(x=30, y=90)
cp.place(x=95, y=90)
bt.place(x=220,y=90)
I'm not sure I understand your question, so the following is an answer based on what I think you're asking.
It works like this: When the Verify button is pressed the verification() function will be called which will initially attempt to parse what the user inputted into a datetime instance. If it cannot do that a error message indicating that will appear. If it succeeds then it next checks to see if it's in the required date range. Again, displaying an error message if it isn't.
from datetime import datetime
from tkinter import *
import tkinter.messagebox as messagebox
DATE_FORMAT = "%d/%m/%Y"
MIN_DATE = datetime.strptime('1/1/2001', DATE_FORMAT)
MAX_DATE = datetime.strptime('31/1/2008', DATE_FORMAT)
def verification():
try:
date_= datetime.strptime(vt.get(), DATE_FORMAT)
except ValueError:
messagebox.showerror('Invalid Date', f'"{vt.get()}"')
return
if MIN_DATE <= date_ < MAX_DATE: # Check date range.
messagebox.showinfo('Bravo', "You entered a valid date!")
else:
messagebox.showerror('Out of range', vt.get())
parent = Tk()
parent.geometry('300x200')
vt = StringVar(value='D/M/Y') # Initially show required format.
lb = Label(parent, text='birth day: ')
cp = Entry(parent, textvariable=vt)
bt = Button(parent, text ='Verify', command=verification)
lb.place(x=30, y=90)
cp.place(x=95, y=90)
bt.place(x=220,y=90)
parent.mainloop()
Screenshot of it running:
I'm trying to build a simple name generator as a project, and I've got it to work, but it doesn't output correctly I'm getting outputs like this:
{NameA}{NameB}NameC NameD{NameE}
While I know for a fact that they are being stored in a list like this:
['Name A', 'NameB', 'NameC', 'NameD', 'NameE']
Here is the full code:
import tkinter as tk
import random
printout = []
def generate():
for _ in range(var1.get()):
C = random.randrange(6)
if C == 0:
printout.append(random.choice(Prefix))
elif 1 <= C <= 2:
printout.append(random.choice(Prefix)+random.choice(Suffix))
elif 3 <= C <= 5:
printout.append(random.choice(Prefix)+" "+random.choice(Prefix)+random.choice(Suffix))
var.set(printout)
print(printout)
root = tk.Tk()
root.title("Simple GUI")
root.geometry("200x200")
var = tk.StringVar()
app = tk.Frame(root)
app.grid()
list1 = [1, 5, 10, 50]
var1 = tk.IntVar(app)
var1.set(1)
drop = tk.OptionMenu(root,var1,*list1)
drop.grid()
label = tk.Label(app, text = "How many results:")
label.grid()
button1 = tk.Button(app, text = "Generate!", command=generate)
button1.grid()
label2= tk.Label(app, textvariable=var)
label2.grid()
with open('D:/My Documents/prefix.txt') as f:
Prefix = [line.rstrip('\n') for line in f]
with open('D:/My Documents/suffix.txt') as r:
Suffix = [line.rstrip('\n') for line in r]
root.mainloop()
I can't find anyone have this problem online so I'm not sure what's happening.
The curly braces you see in your output are a result of Tkinter trying to print a list as if it were a string. You should explicitly convert your list to a string before passing it to var.set.