I am a begginer to python.
I create a graph as below to view on tkinter window.
But It gave me some error.
Error :
figure.set_canvas(self)
AttributeError: 'list' object has no attribute 'set_canvas'
This is my coding part:
import numpy as np
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def f(x, a, b, c):
return a*x**2+b*x+c
xlist = np.linspace(-10, 10, num = 1000)
##print(xlist)
a = 5
b = 1
c = 4
ylist = f(xlist, a, b, c)
plt.figure(num = 0, dpi = 120)
ax = plt.plot(xlist, ylist, label = 'f(x)')
print(type(ax))
plt.title('Plotting Example')
plt.xlabel('Distance / ft')
plt.ylabel('Height / ft')
plt.legend()
plt.grid(True)
# plt.show()
# __________________________________________________________________
my_w = tk.Tk()
my_w.geometry('1000x820+50+50')
my_w.title('data view on tk graph')
wrapper1 = tk.LabelFrame(my_w)
wrapper2 = tk.LabelFrame(my_w)
wrapper1.pack(fill="both", expand="yes", padx=5, pady=5)
wrapper2.pack(fill="both", padx=5, pady=5)
canvas = tk.Canvas(wrapper1, bg="#595656", height=200)
canvas.pack(fill="both", expand=True)
# __________________________________________________________________
plot1 = FigureCanvasTkAgg(ax, canvas)
plot1.draw()
plot1.get_tk_widget().pack(fill="both", expand="yes", padx=5, pady=5)
ctrl_frame = tk.Frame(wrapper2, bg='green', height=100)
ctrl_frame.pack(fill="both")
tk.Button(ctrl_frame, text='View', width=15, command=lambda:None).place(relx=0.9, rely=0.5, anchor=tk.E)
my_w.mainloop()
__________________________________________________________________
Please help me to set the graph on tkinter window
import numpy as np
import tkinter as tk
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# ax = sns.set()
def f(x, a, b, c):
return a * x ** 2 + b * x + c
xlist = np.linspace(-10, 10, num=1000)
a = 5
b = 1
c = 4
ylist = f(xlist, a, b, c)
figure = plt.figure(figsize = (5,4), num = 0, dpi = 120)
figure.add_subplot(111).plot(xlist, ylist)
plt.title('Plotting Example')
plt.xlabel('Distance / ft')
plt.ylabel('Height / ft')
plt.grid(True)
# __________________________________________________________________
my_w = tk.Tk()
my_w.geometry('1000x820+50+50')
my_w.title('data view on tk graph')
wrapper1 = tk.LabelFrame(my_w)
wrapper2 = tk.LabelFrame(my_w)
wrapper1.pack(fill="both", expand="yes", padx=5, pady=5)
wrapper2.pack(fill="both", padx=5, pady=5)
# __________________________________________________________________
plot1 = FigureCanvasTkAgg(figure, wrapper1)
plot1.get_tk_widget().pack(fill="both", expand="yes", padx=5, pady=5)
ctrl_frame = tk.Frame(wrapper2, bg='green', height=100)
ctrl_frame.pack(fill="both")
tk.Button(ctrl_frame, text='View', width=15, command=lambda: None).place(relx=0.9, rely=0.5, anchor=tk.E)
my_w.mainloop()
Related
First I'm sorry for my bad english. I am designing a chatbot with the tkinter as an amateur. I want to add whatsapp-like balloons to the dialog window. I also want the writings to go from the bottom up in the window. I tried to do it as a canvas but it didn't happen. I tried as a label but gave an error.I'd appreciate it if you could help me with that. "TypeError: can only concatenate str (not "Canvas") to str".
The sample design I want
import tkinter as tk
from tkinter import *
import random
import re
import datetime
from tkinter import messagebox
from tkinter.font import Font
root = tk.Tk()
root.title('deneme')
root.geometry('410x600+400+100')
root.config(bg='lightblue')
buton_işlevi=StringVar(root)
buton_işlevi.set("")
#buton oluşturma ve konumu
buton = tk.Button(root, width=10, height=2, relief='raised',state='active',command=lambda :add_text(pencere,giriş,buton_işlevi))
buton.pack()
buton.place(x=310, y=550)
buton.config(text='GÖNDER', bg='lightblue', font='Verdana 8 bold')
root.bind('<Return>',lambda x:add_text(pencere,giriş,buton_işlevi))
#mesaj yazma alanı ve konumu
giriş = tk.Entry(root, textvariable=buton_işlevi,font=('NanumGothic', 12))
giriş.pack()
giriş.place(x=10, y=550, width=290, height=40)
canvas = Canvas(width=300, height=300, bg='white')
canvas.create_oval(200, 200, 300, 300, width=5, fill='red')
#pencere ve konumu
pencere = tk.Text(root, bg='white', yscrollcommand='YES', font=('NanumGothic', 12))
pencere.config(state='disabled')
pencere.pack()
pencere.place(x=10, y=10, width=390, height=530)
#bot ve user mesaj arka plan rengi
pencere.tag_config('bot_renk', background='#fccbc7', foreground='black')
pencere.tag_config('user_renk', background='yellow')
pencere.config(state='normal')
#bot karşılama mesajı
karşılama = 'Hoşgeldiniz'
soru1 = ['merhaba', 'selam']
cevap1 = ["sanada", "iyiyim"]
soru2 = ["deneme", "merhaba", "selam"]
pencere.insert('end', '\nBOT:\t')
pencere.insert('end', karşılama +'\n', 'bot_renk')
#Mesaj ayarları
def add_text(mw,st,imsg):
#mw:message window/st:state/imsg:input message
bot_mesaj=""
user_mesaj = imsg.get()
if user_mesaj in soru1:
user_mesaj='\nUSER :\t'+imsg.get()+'\n'+canvas
bot_mesaj = '\nBOT :\t'+ random.choice(cevap1)+'\n'
mw.config(state='normal')
mw.insert('end',user_mesaj, 'user_renk')
mw.insert('end',bot_mesaj, 'bot_renk')
imsg.set("")
mw.see('end')
mw.config(state='disabled')
elif user_mesaj in soru2:
user_mesaj='\nERÇİN :\t'+imsg.get()+'\n'
bot_mesaj='\nBOT :\t'+ random.choice(cevap2)+'\n'
mw.config(state='normal')
mw.insert('end',user_mesaj, 'user_renk')
mw.insert('end',bot_mesaj, 'bot_renk')
imsg.set("")
mw.see('end')
mw.config(state='disabled')
else :
user_mesaj='\nUSER:\t' +imsg.get()+'\n'
bot_mesaj='\nBOT:\t' + 'Bu kelimeyi henüz öğrenmedim' +'\n'
mw.config(state='normal')
mw.insert('end',user_mesaj, 'user_renk')
mw.insert('end',bot_mesaj, 'bot_renk')
imsg.set("")
mw.see('end')
mw.config(state='disabled')
root.mainloop()
I ran your code and there is no error. But since you mentioned about Whatsapp bubble, here is a basic version you can work on.
from tkinter import *
from datetime import datetime
root = Tk()
root.config(bg="lightblue")
canvas = Canvas(root, width=200, height=200,bg="white")
canvas.grid(row=0,column=0,columnspan=2)
bubbles = []
class BotBubble:
def __init__(self,master,message=""):
self.master = master
self.frame = Frame(master,bg="light grey")
self.i = self.master.create_window(90,160,window=self.frame)
Label(self.frame,text=datetime.now().strftime("%Y-%m-%d %H:%m"),font=("Helvetica", 7),bg="light grey").grid(row=0,column=0,sticky="w",padx=5)
Label(self.frame, text=message,font=("Helvetica", 9),bg="light grey").grid(row=1, column=0,sticky="w",padx=5,pady=3)
root.update_idletasks()
self.master.create_polygon(self.draw_triangle(self.i), fill="light grey", outline="light grey")
def draw_triangle(self,widget):
x1, y1, x2, y2 = self.master.bbox(widget)
return x1, y2 - 10, x1 - 15, y2 + 10, x1, y2
def send_message():
if bubbles:
canvas.move(ALL, 0, -65)
a = BotBubble(canvas,message=entry.get())
bubbles.append(a)
entry = Entry(root,width=26)
entry.grid(row=1,column=0)
Button(root,text="Send",command=send_message).grid(row=1,column=1)
root.mainloop()
i did this mini programme to show databases to the user , i can see buttons of databases but when i press on them borders appear on canvas
from tkinter import *
from tkinter import ttk
import mysql.connector
class mainpro():
def __init__(self):#its my database settings
self.db = mysql.connector.connect(
host="localhost",
user="root",
port=3306,
passwd="1234"
)
self.mycursor = self.db.cursor()
win2 = Toplevel()#idid top level because i did tk before
# Title
win2.title('Manipulate Database')
# geometry
sizex = 1000
sizey = 700
posx = 100
posy = 100
win2.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
# style
style = ttk.Style()
style.theme_use('vista')
style.configure('TLabel', font=('Calibri', 15))
style.configure('TButton', font=('Calibri', 15, 'bold'))
# menu
menu = Menu(win2)
m1 = Menu(menu, tearoff=0)
menu.add_cascade(label='File', menu=m1)
m2 = Menu(menu, tearoff=0)
menu.add_cascade(label='DLL', menu=m2)
m3 = Menu(menu, tearoff=0)
menu.add_cascade(label='DML', menu=m3)
m4 = Menu(menu, tearoff=0)
menu.add_cascade(label='Help', menu=m4)
m1.add_command(label='Show databases', command=lambda: showdata())
win2.config(menu=menu)
def showdata():
def event(event):
canvas.config(scrollregion=canvas.bbox("all"))
self.mycursor.execute('SHOW DATABASES')
list = self.mycursor.fetchall()
canvas = Canvas(win2, width=1000, height=700)
f1 = Frame(canvas)
canvas.create_window((0, 0), window=f1, anchor='nw')
scroll = Scrollbar(win2, orient="vertical", command=canvas.yview)
scroll.pack(side="right", fill="y")
canvas.configure(yscrollcommand=scroll.set)
canvas.pack()
f1.bind("<Configure>", event)
y = 0
for x in list:
y += 1
ttk.Label(f1, text=str(y) + '-').grid(column=0, row=y, padx=10, pady=10, sticky='w')
ttk.Button(f1, text=x, width=35).grid(column=1, row=y, padx=10, pady=10, sticky='w')
win2.mainloop()
mainpro()
help please
You could try adding highlightthickness=0:
canvas = Canvas(win2, width=1000, height=700, highlightthickness=0)
Try this,
Source: Check
import tkinter # assuming Python 3 for simplicity's sake
import tkinter.ttk as ttk
root = tkinter.Tk()
f = tkinter.Frame(relief='flat')
lF = ttk.LabelFrame(root, labelwidget=f, borderwidth=4)
lF.grid()
b = ttk.Button(lF, text='')
b.grid()
root.mainloop()
Or try this
Canvas=Canvas(self,width=width/2,height=height/2,bg=bgCanvasColor,borderwidth=0, highlightthickness=0)
I'm trying to display equations by using GUI. I use latex and canvas. However, I'm getting an error message ValueError: KeyPress event keysym=Return keycode=36 char='\r' x=266 y=8
it should be working because I have already converted python expressions into Latex's.
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
import matplotlib.pyplot as plt
from tkinter import *
from sympy import *
matplotlib.use('TkAgg')
root=Tk()
frame=Frame(root)
frame.pack()
frame1= Frame()
frame1.pack()
caracter=StringVar()
def result(caracter):
a = str(caracter)
text1=latex(a)
ax.clear()
ax.text(0.2, 0.6, "$"+text1+"$", fontsize = 6)
canvas.draw()
def element(num):
caracter.set(caracter.get()+num)
#-----------------------------SCREEN------------
screen=Entry(frame, width=50, textvariable=caracter)
screen.pack()
screen.grid(row=1, column=1, pady=10, columnspan=5)
#-----------------------BUTTONS-----------------------
go=Button(frame, height=1, text="Go")
go.grid(row=1, column=6)
Buttonx=Button(frame, text="x", width=5, padx=0, pady=2, command=lambda:element("x"))
Buttonx.grid(row=2, column=6)
#--------CANVAS ---------------
label = Label(frame1)
label.pack()
fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=label)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
root.bind('<Return>', result)
root.mainloop()
This is the shortest code to reproduce the issue. Any help or hint will be appreciated. Thank you very much in advance
You are passing the char associated with <RETURN> to your function result. Because the parameter is named caracter, this shadows the variable caracter declared earlier as a tk.StringVar.
something like this should give you the expected result:
def result(dummy_c):
a = caracter.get()
text1 = latex(a)
ax.clear()
ax.text(0.2, 0.6, "$"+text1+"$", fontsize = 6)
canvas.draw()
I've just started writing Python a month ago and now getting into Tkinter. I'm trying to build a program that a user can open an excel file into Tkinter, display the dataframe and the user can choose a certain graph type, insert the variables for the X-axis and Y-axis and plot it. I've build the general layout of the GUI using PAGE but having problems on how to give commands to the widgets on displaying the dataframe and plotting the graph.
Here's my code for the GUI:
import sys
from tkinter.filedialog import askopenfilename
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except ImportError:
import tkinter.ttk as ttk
py3 = 1
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = Tk()
top = New_Toplevel_1 (root)
root.mainloop()
w = None
def create_New_Toplevel_1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = Toplevel (root)
top = New_Toplevel_1 (w)
return (w, top)
def destroy_New_Toplevel_1():
global w
w.destroy()
w = None
class New_Toplevel_1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
self._bgcolor = '#d9d9d9' # X11 color: 'gray85'
self._fgcolor = '#000000' # X11 color: 'black'
self._compcolor = '#d9d9d9' # X11 color: 'gray85'
self._ana1color = '#d9d9d9' # X11 color: 'gray85'
self._ana2color = '#d9d9d9' # X11 color: 'gray85'
top.geometry("757x1037+832+67")
top.title("New Toplevel 1")
top.configure(background="#d9d9d9")
top.configure(highlightbackground="#d9d9d9")
top.configure(highlightcolor="black")
self.Canvas1 = Canvas(top)
self.Canvas1.place(relx=0.04, rely=0.58, relheight=0.4, relwidth=0.92)
self.Canvas1.configure(background="white")
self.Canvas1.configure(borderwidth="2")
self.Canvas1.configure(highlightbackground="#d9d9d9")
self.Canvas1.configure(highlightcolor="black")
self.Canvas1.configure(insertbackground="black")
self.Canvas1.configure(relief=RIDGE)
self.Canvas1.configure(selectbackground="#c4c4c4")
self.Canvas1.configure(selectforeground="black")
self.Canvas1.configure(width=695)
self.Button2 = Button(top)
self.Button2.place(relx=0.75, rely=0.52, height=42, width=138)
self.Button2.configure(activebackground="#d9d9d9")
self.Button2.configure(activeforeground="#000000")
self.Button2.configure(background="#d9d9d9")
self.Button2.configure(disabledforeground="#a3a3a3")
self.Button2.configure(foreground="#000000")
self.Button2.configure(highlightbackground="#d9d9d9")
self.Button2.configure(highlightcolor="black")
self.Button2.configure(pady="0")
self.Button2.configure(text='''Generate Graph''')
self.Labelframe1 = LabelFrame(top)
self.Labelframe1.place(relx=0.05, rely=0.39, relheight=0.18
, relwidth=0.44)
self.Labelframe1.configure(relief=GROOVE)
self.Labelframe1.configure(foreground="black")
self.Labelframe1.configure(text='''Type of Graph''')
self.Labelframe1.configure(background="#d9d9d9")
self.Labelframe1.configure(highlightbackground="#d9d9d9")
self.Labelframe1.configure(highlightcolor="black")
self.Labelframe1.configure(width=330)
self.Radiobutton1 = Radiobutton(self.Labelframe1)
self.Radiobutton1.place(relx=0.06, rely=0.22, relheight=0.2
, relwidth=0.31)
self.Radiobutton1.configure(activebackground="#d9d9d9")
self.Radiobutton1.configure(activeforeground="#000000")
self.Radiobutton1.configure(background="#d9d9d9")
self.Radiobutton1.configure(disabledforeground="#a3a3a3")
self.Radiobutton1.configure(foreground="#000000")
self.Radiobutton1.configure(highlightbackground="#d9d9d9")
self.Radiobutton1.configure(highlightcolor="black")
self.Radiobutton1.configure(justify=LEFT)
self.Radiobutton1.configure(text='''Bar Chart''')
self.Radiobutton2 = Radiobutton(self.Labelframe1)
self.Radiobutton2.place(relx=0.06, rely=0.38, relheight=0.2
, relwidth=0.35)
self.Radiobutton2.configure(activebackground="#d9d9d9")
self.Radiobutton2.configure(activeforeground="#000000")
self.Radiobutton2.configure(background="#d9d9d9")
self.Radiobutton2.configure(disabledforeground="#a3a3a3")
self.Radiobutton2.configure(foreground="#000000")
self.Radiobutton2.configure(highlightbackground="#d9d9d9")
self.Radiobutton2.configure(highlightcolor="black")
self.Radiobutton2.configure(justify=LEFT)
self.Radiobutton2.configure(text='''Histogram''')
self.Radiobutton3 = Radiobutton(self.Labelframe1)
self.Radiobutton3.place(relx=0.06, rely=0.54, relheight=0.2
, relwidth=0.37)
self.Radiobutton3.configure(activebackground="#d9d9d9")
self.Radiobutton3.configure(activeforeground="#000000")
self.Radiobutton3.configure(background="#d9d9d9")
self.Radiobutton3.configure(disabledforeground="#a3a3a3")
self.Radiobutton3.configure(foreground="#000000")
self.Radiobutton3.configure(highlightbackground="#d9d9d9")
self.Radiobutton3.configure(highlightcolor="black")
self.Radiobutton3.configure(justify=LEFT)
self.Radiobutton3.configure(text='''Scatter Plot''')
self.Button3 = Button(top)
self.Button3.place(relx=0.28, rely=0.05, height=52, width=122)
self.Button3.configure(activebackground="#d9d9d9")
self.Button3.configure(activeforeground="#000000")
self.Button3.configure(background="#d9d9d9")
self.Button3.configure(disabledforeground="#a3a3a3")
self.Button3.configure(foreground="#000000")
self.Button3.configure(highlightbackground="#d9d9d9")
self.Button3.configure(highlightcolor="black")
self.Button3.configure(pady="0")
self.Button3.configure(text='''Browse''')
self.Button3.configure(width=122)
self.Button3.configure(command=askopenfilename)
self.Label5 = Label(top)
self.Label5.place(relx=0.03, rely=0.06, height=31, width=147)
self.Label5.configure(activebackground="#f9f9f9")
self.Label5.configure(activeforeground="black")
self.Label5.configure(background="#d9d9d9")
self.Label5.configure(disabledforeground="#a3a3a3")
self.Label5.configure(foreground="#000000")
self.Label5.configure(highlightbackground="#d9d9d9")
self.Label5.configure(highlightcolor="black")
self.Label5.configure(text='''Upload File:''')
self.Label5.configure(width=147)
self.Label3 = Label(top)
self.Label3.place(relx=0.05, rely=0.13, height=31, width=111)
self.Label3.configure(background="#d9d9d9")
self.Label3.configure(disabledforeground="#a3a3a3")
self.Label3.configure(foreground="#000000")
self.Label3.configure(text='''Data Frame :''')
self.Text1 = Text(top)
self.Text1.place(relx=0.05, rely=0.16, relheight=0.21, relwidth=0.9)
self.Text1.configure(background="white")
self.Text1.configure(font="TkTextFont")
self.Text1.configure(foreground="black")
self.Text1.configure(highlightbackground="#d9d9d9")
self.Text1.configure(highlightcolor="black")
self.Text1.configure(insertbackground="black")
self.Text1.configure(selectbackground="#c4c4c4")
self.Text1.configure(selectforeground="black")
self.Text1.configure(width=684)
self.Text1.configure(wrap=WORD)
self.Labelframe2 = LabelFrame(top)
self.Labelframe2.place(relx=0.5, rely=0.39, relheight=0.12
, relwidth=0.45)
self.Labelframe2.configure(relief=GROOVE)
self.Labelframe2.configure(foreground="black")
self.Labelframe2.configure(text='''Labelframe''')
self.Labelframe2.configure(background="#d9d9d9")
self.Labelframe2.configure(width=340)
self.Label1 = Label(self.Labelframe2)
self.Label1.place(relx=0.03, rely=0.24, height=31, width=67)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''X-axis :''')
self.Label2 = Label(self.Labelframe2)
self.Label2.place(relx=0.03, rely=0.56, height=31, width=66)
self.Label2.configure(background="#d9d9d9")
self.Label2.configure(disabledforeground="#a3a3a3")
self.Label2.configure(foreground="#000000")
self.Label2.configure(text='''Y-axis :''')
self.Entry1 = Entry(self.Labelframe2)
self.Entry1.place(relx=0.24, rely=0.24, relheight=0.29, relwidth=0.72)
self.Entry1.configure(background="white")
self.Entry1.configure(disabledforeground="#a3a3a3")
self.Entry1.configure(font="TkFixedFont")
self.Entry1.configure(foreground="#000000")
self.Entry1.configure(insertbackground="black")
self.Entry1.configure(width=244)
self.Entry2 = Entry(self.Labelframe2)
self.Entry2.place(relx=0.24, rely=0.56, relheight=0.29, relwidth=0.72)
self.Entry2.configure(background="white")
self.Entry2.configure(disabledforeground="#a3a3a3")
self.Entry2.configure(font="TkFixedFont")
self.Entry2.configure(foreground="#000000")
self.Entry2.configure(insertbackground="black")
self.Entry2.configure(width=244)
if __name__ == '__main__':
vp_start_gui()
I know how to save the data into a dataframe and plot graphs in Python, but i'm not sure where to write those codes when GUI is involved. All i was able to do was give a command to the 'Browse' button to search for the excel file.
self.Button3.configure(command=askopenfilename)
Can someone help me:
How to save the excel file chosen from the command into a dataframe
How to display the dataframe into the textbox below
How to plot the graph with the criteria (type of graph and axes) chosen onto the canvas at bottom
Thanks so much in advance.
In class use some self.variable to keep information and then you can use it in other methods in class.
In example I use method load() to load file and create dataframe, and method display() to display this dataframe in text widget.
try:
# Python 2
import Tkinter as tk
import ttk
from tkFileDialog import askopenfilename
except ImportError:
# Python 3
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
import pandas as pd
# --- classes ---
class MyWindow:
def __init__(self, parent):
self.parent = parent
self.filename = None
self.df = None
self.text = tk.Text(self.parent)
self.text.pack()
self.button = tk.Button(self.parent, text='LOAD DATA', command=self.load)
self.button.pack()
self.button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
self.button.pack()
def load(self):
name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xlsx'))])
if name:
if name.endswith('.csv'):
self.df = pd.read_csv(name)
else:
self.df = pd.read_excel(name)
self.filename = name
# display directly
#self.text.insert('end', str(self.df.head()) + '\n')
def display(self):
# ask for file if not loaded yet
if self.df is None:
self.load()
# display if loaded
if self.df is not None:
self.text.insert('end', self.filename + '\n')
self.text.insert('end', str(self.df.head()) + '\n')
# --- main ---
if __name__ == '__main__':
root = tk.Tk()
top = MyWindow(root)
root.mainloop()
Here i have fetch the excel data and store it in the graph, but i want my graph should plot data after 5 second,and the graph should run in the Run time.
from openpyxl import load_workbook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# read from excel file
wb = load_workbook('C:\\Users\\Acer-i5-607\\Desktop\\case1.xlsx')
sheet_1 = wb.get_sheet_by_name('case1')
plt.figure(figsize=(6, 4), facecolor='Grey')
G = gridspec.GridSpec(6, 2)
axes_1 = plt.subplot(G[0, :])
x = np.zeros(sheet_1.max_row)
y = np.zeros(len(x))
for i in range(1, sheet_1.max_row):
x[i] = sheet_1.cell(row=i + 1, column=2).value
y[i] = sheet_1.cell(row=i + 1, column=4).value
#print x
#print y
# create the plot
plt.xlabel('time')
plt.ylabel('HR')
plt.plot(x, y, color='cyan', label='HR')
plt.legend(loc='upper right', fontsize='small')
plt.grid(True)
#plt.title('Reading values from an Excel file'
axes_1 = plt.subplot(G[1, :])
x = np.zeros(sheet_1.max_row)
y = np.zeros(len(x))
for i in range(1, sheet_1.max_row):
x[i] = sheet_1.cell(row=i + 1, column=2).value
y[i] = sheet_1.cell(row=i + 1, column=6).value
#print a
#print b
# create the plot
plt.xlabel('time')
plt.ylabel('Pulse')
plt.plot(x, y, color='red', label='Pulse')
plt.legend(loc='upper right', fontsize='small')
plt.grid(True)
axes_1 = plt.subplot(G[2, :])
x = np.zeros(sheet_1.max_row)
y = np.zeros(len(x))
for i in range(1, sheet_1.max_row):
x[i] = sheet_1.cell(row=i + 1, column=2).value
y[i] = sheet_1.cell(row=i + 1, column=7).value
#print x
#print y
# create the plot
plt.xlabel('time')
plt.ylabel('SpO2')
plt.plot(x, y, color='magenta', label='SpO2')
plt.legend(loc='upper right', fontsize='small')
plt.grid(True)
axes_1 = plt.subplot(G[3, :])
x = np.zeros(sheet_1.max_row)
y = np.zeros(len(x))
for i in range(1, sheet_1.max_row):
x[i] = sheet_1.cell(row=i + 1, column=2).value
y[i] = sheet_1.cell(row=i + 1, column=8).value
#print x
#print y
# create the plot
plt.xlabel('time')
plt.ylabel('Perf')
plt.plot(x, y, color='blue', label='Perf')
plt.legend(loc='upper right', fontsize='small')
plt.grid(True)
axes_1 = plt.subplot(G[4, :])
x = np.zeros(sheet_1.max_row)
y = np.zeros(len(x))
for i in range(1, sheet_1.max_row):
x[i] = sheet_1.cell(row=i + 1, column=2).value
y[i] = sheet_1.cell(row=i + 1, column=9).value
#print x
#print y
# create the plot
plt.xlabel('time')
plt.ylabel('etCO2')
plt.plot(x, y, color='yellow', label='etCO2')
plt.legend(loc='upper right', fontsize='small')
plt.grid(True)
axes_1 = plt.subplot(G[5, :])
x = np.zeros(sheet_1.max_row)
y = np.zeros(len(x))
for i in range(1, sheet_1.max_row):
x[i] = sheet_1.cell(row=i + 1, column=2).value
y[i] = sheet_1.cell(row=i + 1, column=10).value
#print x
#print y
# create the plot
plt.xlabel('time')
plt.ylabel('imCO2')
plt.plot(x, y, color='green', label='imCO2')
plt.legend(loc='upper right', fontsize='small')
plt.grid(True)
plt.xlim(0, 60000)
plt.ylim(0, 100)
plt.show()
import tkinter as tk
from tkinter import filedialog
import pandas as pd
import matplotlib.pyplot as plt
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue')
canvas1.pack()
def getExcel ():
global df
import_file_path = filedialog.askopenfilename()
df = pd.read_excel (import_file_path)
df["Year"] = pd.to_datetime(df["Year"], format="%Y")
ax = df.plot("Year", "Accidents",marker='o',color='r')
plt.grid()
plt.title('Yearly Graph')
ax.figure.autofmt_xdate()
plt.show()
browseButton_Excel = tk.Button(text='Import Excel File', command=getExcel, bg='green', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 150, window=browseButton_Excel)
root.mainloop()
So I'm working on a radiance to apparent temperature calculator tool to integrate into a data analysis program with lots of different functions. My "test code" ran fine on it's own outside of my main program and gave correct results.
Code that works:
from numpy import arange, exp, vectorize, size, zeros, seterr, where, log10, all
from scipy.constants import h,c,k,pi
from scipy.interpolate import interp1d
from scipy.integrate import quad
def planck_l(l, T):
c1 = 2*h*c**2
c2 = h*c / k
M = (c1/l**5) * (1 / (exp(c2/(l*T))-1))
return M
def planck_p(l, T):
c1 = 2*pi*c
c2 = h*c / k
M = (c1/(pi*l**4)*(1/(exp(c2/(l*T))-1)))
return M
def integrand(planck, lband, rband, T):
return quad(planck, lband, rband, args=T)[0]
def getRadiance(planck,lband,rband,T):
int_planck = vectorize(integrand)
return int_planck(planck,lband,rband,T)
def rad2t(rad, l, r):
temps = arange(0, 5000)
radiance = []
for t in temps:
radiance.append(integrand(planck_l, l/1e6, r/1e6, t)/100/100)
f = interp1d(radiance, temps)
T = f(rad)
return T
However when I integrate this code into my main tkinter GUI loop, the integrand function I've defined only returns values of 0.0. Code that doesn't work:
import tkinter as tk
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
from tkinter import filedialog, messagebox
from glob import glob
import re
import os
import sys
import tkinter.scrolledtext as tkst
import struct
import cv2
import csv
from scipy.constants import h, c, k, pi
from scipy.integrate import quad
from scipy.interpolate import interp1d
import bigfloat
def planck_l(l, T):
c1 = 2*h*c**2
c2 = h*c / k
M = (c1/l**5) * (1 / (np.exp(c2/(l*T))-1))
return M
def planck_p(l, T):
c1 = 2*pi*c
c2 = h*c / k
M = (c1/(pi*l**4)*(1/(np.exp(c2/(l*T))-1)))
return M
def integrand(planck, lband, rband, T):
return quad(planck, lband, rband, args=T)[0]
def getRadiance(planck,lband,rband,T):
int_planck = np.vectorize(integrand)
return int_planck(planck, lband, rband, T)
def rad2T(rad, l, r):
temps = np.arange(0, 5000)
radiance = []
for t in temps:
radiance.append(integrand(planck_l, l/1e6, r/1e6, t)/100/100)
f = interp1d(radiance, temps)
T = f(rad)
return T
#.......... other definitions, main window/widget building etc. ...........
def rad_t_conv(self, coor):
window = tk.Toplevel(self)
window.geometry(coor[0] + coor[1])
window.grab_set()
Label(window, text='Set Wavelength Range (um): ').grid(row=0, column=0, columnspan=2)
range = StringVar()
range.set('3-5')
range_enter = Entry(window, textvariable=range, width=10)
range_enter.grid(row=1, column=0)
window.rngsub = tk.Button(window, text='Save', command=lambda: self.submit(range_enter, range))
window.rngsub.grid(row=2, column=0)
Label(window, text='Radiance:').grid(row=3, column=0)
rad = StringVar()
rad_enter = Entry(window, textvariable=rad, width=10)
rad_enter.grid(row=4, column=0)
window.radsub = tk.Button(window, text='Calculate App. Temp', command=lambda: self.combine(self.submit(rad_enter, rad), self.calc_temp(rad.get(), range.get(), t_enter, temp)))
window.radsub.grid(row=5, column=0)
Label(window, text='App. Temperature:').grid(row=3, column=1)
temp = StringVar()
t_enter = Entry(window, textvariable=temp, width=10)
t_enter.grid(row=4, column=1)
window.tempsub = tk.Button(window, text='Calculate Radiance', command=lambda: self.combine(self.submit(t_enter, temp), self.calc_rad(temp.get(), range.get(), rad_enter, rad)))
window.tempsub.grid(row=5, column=1)
def calc_temp(self, rad, range, temp_ent, temp):
range = range.split('-')
rad = float(rad)
l = float(range[0])
r = float(range[1])
T = rad2t(rad, l, r)
temp.set(str(T))
self.update_idletasks()
def calc_rad(self, temp, range, rad_ent, rad):
range = range.split('-')
l = int(range[0])
r = int(range[1])
temp = float(temp)
radiance = integrand(planck_l, l/1e6, r/1e6, temp)/100/100
print(radiance)
rad.set(str(radiance))
self.update_idletasks()
I thought it was maybe a rounding issue but utilizing bigfloat had no effect. I'm truly puzzled as to why it would work outside of my main code and then fail in this way when integrated. I've been scouring the rest of my tkinter gui window code for anything that could be effecting it but I'm pretty stumped. Any help, or guesses even, are much appreciated. I can post more of my main code if requested but it's honestly a giant mess since I've been using pyinstaller to compile it into an .exe and it needs to have all non-module functions defined within the same file. To answer #jsbueno, my call to rad_t_conv is from a button in my main window.
self.rad2t_start = tk.Button(self, text='Radiance/Apparent Temp Conversion', command=lambda: self.rad_t_conv(coor))
self.rad2t_start.grid(row=0, column=2, pady=5)
Class is defined as such:
class Application(tk.Frame):
And then called as:
root = tk.Tk()
w = 700 # width for the Tk root
h = 500 # height for the Tk root
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
app = Application(master=root)
app.pack(side="top", fill="both", expand=True)
root.mainloop()
The combine function is:
def combine(self, *funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func