Line graph only appears a half in the gut - python

I try to make a line graph with python and the graph only appears a half of the canvas and the rest is only black in the GUI. The data that should be appear was taken from the database.
###----------------Connecting to the database-------------#####
import sqlite3
DB = sqlite3.connect ("personal_project.db")
CURSOR = DB.cursor()
###----------------create the SQL command to create the table and save data-------------######
COMMAND1 = """CREATE TABLE IF NOT EXISTS
balance (
UserID INTEGER PRIMARY KEY,
Date TEXT,
Amount TEXT,
Descriotion)"""
CURSOR.execute(COMMAND1)
from tkinter import *
from tkinter import messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
###----------------Create the window-------------#####
main_WINDOW = Tk()
main_WINDOW.title("Study App")
main_WINDOW.geometry("1940x1080")#width*length
main_WINDOW.configure(bg="#ffffff")
###------Show Information Using Graph-------###
graquery = '''SELECT Date, Amount FROM balance'''
CURSOR.execute(graquery)
graresults = CURSOR.fetchall()
Date = [result[0] for result in graresults]
Amount = [result[1] for result in graresults]
figure = plt.figure()
plt.plot(Date, Amount)
plt.xlabel('Date')
plt.ylabel('Amount')
plt.title('Balance graph Graph')
gracanvas = Canvas(main_WINDOW, width=1070, height=452)
gracanvas.place(x=356, y=270)
figure_canvas = FigureCanvasTkAgg(figure, gracanvas)
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget(), anchor="nw")
main_WINDOW.mainloop()

Related

Line graph only appears a little bit in the top and

I try to make a line graph with python and the graph only appears a little in the end of the canvas in the GUI. The data that should be paper was taken from the database.
enter image description here
import sqlite3 ###----------------Connecting to the database-------------#####
DB = sqlite3.connect ("personal_project.db")
CURSOR = DB.cursor()
###----------------create the SQL command to create the table and save data-------------######
COMMAND1 = """CREATE TABLE IF NOT EXISTS
balance (
UserID INTEGER PRIMARY KEY,
Date TEXT,
Amount TEXT,
Descriotion)"""
CURSOR.execute(COMMAND1)
from tkinter import *
from tkinter import messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
###----------------Create the window-------------#####
main_WINDOW = Tk()
main_WINDOW.title("Study App")
main_WINDOW.geometry("1940x1080")#width*length
main_WINDOW.configure(bg="#ffffff")
###------Show Information Using Graph-------###
graquery = '''SELECT Date, Amount FROM balance'''
CURSOR.execute(graquery)
graresults = CURSOR.fetchall()
Date = [result[0] for result in graresults]
Amount = [result[1] for result in graresults]
figure = plt.figure()
plt.plot(Date, Amount)
plt.xlabel('Date')
plt.ylabel('Amount')
plt.title('Balance graph Graph')
gracanvas = Canvas(main_WINDOW, width=1070, height=452)
gracanvas.pack()
gracanvas.place(x=356, y=270)
figure_canvas = FigureCanvasTkAgg(figure, gracanvas)
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget())
Consider this code:
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget())
The create_window method by default centers the window at the given coordinate, which is what your image looks like. If you want the top-left corner of the window to be at 0,0, specify anchor="nw" so that the northwest corner of the window is at the given coordinate.
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget(), anchor="nw")
# ^^^^^^^^^^^

Based on a Tkinter calendar a sqlite3 query between dates in unix timestamp

I'm trying to create a script based on a datepicker in Python and Tkinter. I can pick a date, start and end date, convert it to unix timestamp, but when I query a sqlite3 database, the response is:
File "/home/frits/Documents/python_datetime/cal.py", line 46, in <module>
c.execute('SELECT * from RecordOne where ct = ?' % unix_timea, (unix_timeb,))
TypeError: not all arguments converted during string formatting
I thought bij converting the unix_time variables to integers solves the problem, but no.
I don't see the error..
Can anyone point out my mistake?
My terrible bad code is:
import datetime
from datetime import timedelta
import time
import sqlite3
def get_date():
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
def cal_done():
top.withdraw()
root.quit()
root = tk.Tk()
root.withdraw() # keep the root window from appearing
top = tk.Toplevel(root)
cal = Calendar(top,
font="Arial 14", selectmode='day',
cursor="hand1")
cal.pack(fill="both", expand=True)
ttk.Button(top, text="ok", command=cal_done).pack()
selected_date = None
root.mainloop()
return cal.selection_get()
selection = get_date()
dt = selection
start = dt - timedelta(days=dt.weekday())
unix_time = time.mktime(start.timetuple())
unix_timea= int(unix_time)
print(unix_timea)
end = start + timedelta(days=6)
unix_time1 = time.mktime(end.timetuple())
unix_timeb = int(unix_time1)
print(unix_timeb)
conn = sqlite3.connect('monitor.db')
c = conn.cursor()
c.execute('SELECT * from RecordOne where ct = ?' % unix_timea, (unix_timeb,))
test = c.fetchall()
for row in test:
print(row)
.

How to imbed figure object when plotting occurs outside tkinter environment

There are plenty of web examples (1,2,3,4) and threads (1,2,3) about imbedding a plot into a tkinter window, but very few that address plotting in a separate environment and importing the resulting graph to the tkinter window.
In a nutshell, I have a program that calculates many different values, and exports those values to a separate file that creates a large number of plots. My tkinter application accepts parameters in Entry boxes, before applying them to the main file that does all the calculations. Typically, I would just follow the examples I linked, but with such a large number of plots being generated and the need to be able to select any particular graph I need at a given time, this would be inefficient and time consuming to brute-force. There must be a better way!
Below is a simplified example of how I am trying to accomplish this task:
import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
import numpy as np
def example_plot(A):
# Plot generated outside of tkinter environment, but controlled by
# variable within tkinter window.
x = np.linspace(0, 10, 50)
y = A*x**2
fig, ax = plt.subplots()
ax.plot(x,y)
ax.set_xlabel('x')
ax.set_ylabel('y')
return fig
window = tk.Tk()
window.geometry('256x256')
variableEntry = tk.Entry(width = 10)
variableLabel = tk.Label(window, text = "A")
variableEntry.grid(row = 0, column = 0)
variableLabel.grid(row = 0, column = 1)
def plotButton():
A = variableEntry.get()
A = int(A)
figure = Figure(figsize = (1,1), dpi = 128)
add = figure.add_subplot(1,1,1)
example = example_plot(A)
add.imshow(example)
canvas = FigureCanvasTkAgg(figure)
canvas.get_tk_widget().grid(row = 2, column = 0)
toolbar = NavigationToolbar2Tk(canvas)
toolbar.update()
canvas._tkcanvas.grid(row = 3 , column = 0)
canvas.show()
applyButton = tk.Button(master = window, text = "Apply", command = plotButton)
applyButton.grid(row = 1,column = 0)
window.mainloop()
When I run this, set A to some integer and press apply, I get an error
TypeError: Image data of dtype object cannot be converted to float
It seems that add.imshow() doesn't like that I fed it the figure. Is there some way to obtain the figure (ie: example = example_plot(A)) and store it to display later?
Try this:
import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, \
NavigationToolbar2Tk
import numpy as np
def example_plot(A):
# Plot generated outside of tkinter environment, but controlled by
# variable within tkinter window.
x = np.linspace(0, 10, 50)
y = A*x*x # This should run slightly faster
fig, ax = plt.subplots()
ax.plot(x,y)
ax.set_xlabel("x")
ax.set_ylabel("y")
return fig
window = tk.Tk()
frame = tk.Frame(window)
frame.pack()
variable_entry = tk.Entry(frame, width=10)
variable_label = tk.Label(frame, text="A")
variable_entry.pack(side="left", fill="x")
variable_label.pack(side="left")
def plot():
A = int(variable_entry.get())
figure = Figure(figsize=(1, 1), dpi=128)
add = figure.add_subplot(1, 1, 1)
figure = example_plot(A)
canvas = FigureCanvasTkAgg(figure)
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2Tk(canvas, window)
toolbar.update()
canvas.get_tk_widget().pack()
# canvas.show() # There is no need for this
apply_button = tk.Button(window, text="Apply", command=plot)
apply_button.pack(fill="x")
window.mainloop()
Your example_plot returns a Figure so you can use figure = example_plot(A) and then FigureCanvasTkAgg(figure). I also added a frame and tried to make everything look better.

get variable of combobox for sqllite query in tkinter

i have an issue that i want to query from combo box value selected from sqllite database and show in graph,here is my code.I will be appreciate any one could help me.
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import pandas as pd
import sqlite3
from sqlalchemy import create_engine
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
def imprt_data():
import_file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")],
title = "Choose a file")
df = pd.read_excel(import_file_path)
return df
def svetosql():
df=imprt_data()
engine = create_engine('sqlite:///save_pandas.db', echo=True)
sqlite_connection = engine.connect()
sqlite_table="Data"
df.to_sql(sqlite_table, sqlite_connection, if_exists='fail')
def sqlconection():
con=sqlite3.connect('save_pandas.db')
c = con.cursor()
return c
def callback_obj(event):
comboobject=event.widget.get()
return (comboobject)
def callback_rgn(event):
comboregion=event.widget.get()
return (comboregion)
root=tk.Tk()
root.title('Testing Tkinter Combobox With Sqllite')
root.geometry('500x500')
##---------Widget---------------
comboregion=ttk.Combobox(root,width=50 , height=20)
c=sqlconection()
for row in c.execute('SELECT DISTINCT Data.شهرستان from data '):
Query = [row[0] for row in c.fetchall()]
comboregion['values']=Query
comboregion.pack( ipadx=2, ipady=2 )
selectvalueregion=comboregion.bind("<<ComboboxSelected>>", callback_rgn)
#------------------------
comboobject=ttk.Combobox(root,width=50 , height=20)
c=sqlconection()
for row in c.execute('SELECT DISTINCT from Data '):
Query = [member[0] for member in c.description]
comboobject['values']=Query
comboobject.pack( ipadx=2, ipady=2 )
selectvalueobject=comboobject.bind("<<ComboboxSelected>>", callback_obj)
for row in c.execute('SELECT DISTINCT * from Data WHERE region LIKE ? ;' , (selectvalueobject,)):
Q = [row[0] for row in c.fetchall()]
print(Q)
#------------------------
f = Figure(figsize=(5,5), dpi=80)
a = f.add_subplot(111)
a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
canvas = FigureCanvasTkAgg(f, root)
canvas.draw()
canvas.get_tk_widget().pack(ipadx=2, ipady=2)
root.mainloop()
the graph has some data only for show,but i want to get data from combo box and then make query from database and after that show in graph.
if any one want to get database ,please leave comments.

Why Aren't My Values Showing Up In My Sqlite Database When Imported From Tkinter In Python 3

Its Not Giving Any Errors Just Not Showing Up If it seems a little choppy sorry been getting frustrated but literally everything works no errors at all it even enters the camper id but no name someone please help, thank you, and dont down this please been getting allot of strikes even though most of the people dont actually read the code [FIXED]
import tkinter
from tkinter import *
import random
from random import randint
import sqlite3
from sqlite3 import *
#creating screen
page = tkinter.Tk()
#naming screen
page.title('Camp Sign-up')
#setting screen size
page.geometry("1000x500")
#creating text
Title = tkinter.Label(page, text='Registration', font=('arial') ).pack()
FullName = tkinter.Label(page, text='Full Name:', font=('arial')).place(x=110, y=50)
full = StringVar()
FullNameValue = Entry(page, textvar=full, width=25,).place(x=200, y=53)
CamperID = random.randint(100000, 1000000)
#Database
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
def createtable():
c.execute("""CREATE TABLE Registration (
CampID INT,
full TEXT,
)""")
try:
createtable()
except:
sqlite3.OperationalError
#button
def buttonclick():
#heres where you lnk where you want your info to go
FullNameValu= full.get()
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
c.execute("INSERT INTO Registration(CampID, full)VALUES(?, ?)",(CamperID, FullNameValu))
conn.commit()
#button
work = Button(page, text='Submit', width=10, height=2, bg='lightgrey',
command=buttonclick()).place(x=475, y=450)
#heres where you execute your close files commands
conn.commit()
c.close()
conn.close()
#ending code never put this above anything
page.mainloop()
Your buttonclick() run as soon as you start the program cause have done this way command=buttonclick() which suppose to be command=buttonclick. Also your creation of your database is not good have changed that and refactor your all code.
import tkinter
from tkinter import *
import random
from random import randint
import sqlite3
from sqlite3 import *
# THIS IS CREATING DATABASE
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS Registration (CampID INT, full TEXT)""")
conn.commit()
conn.close()
#button
def buttonclick():
#heres where you lnk where you want your info to go
FullNameValu= full.get()
# generating the camp id
CamperID = random.randint(100000, 1000000)
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
c.execute("INSERT INTO Registration(CampID, full)VALUES(?, ?)",(CamperID, FullNameValu))
conn.commit()
conn.close()
print("records inserted")
#creating screen
page = tkinter.Tk()
#naming screen
page.title('Camp Sign-up')
#setting screen size
page.geometry("1000x500")
#creating text
Title = tkinter.Label(page, text='Registration', font=('arial') )
Title.pack()
FullName = tkinter.Label(page, text='Full Name:', font=('arial'))
FullName.place(x=110, y=50)
full = StringVar()
FullNameValue = Entry(page, textvar=full, width=25,)
FullNameValue.place(x=200, y=53)
#button
work = Button(page, text='Submit', width=10, height=2, bg='lightgrey',
command=buttonclick).place(x=475, y=450)
page.mainloop()

Categories