Upload txt file to draw xy graph python - python

my name is Vo Minh Hoang. I wrote a Python program to upload file to draw graph but i have one problem which is the button to draw graph. Please help me and thank you very much. I send an image which is an example I want to complete the program.
from tkinter import *
from tkinter import filedialog
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
# functions
def openFile():
tf = filedialog.askopenfilename(
initialdir="C:/Users/MainFrame/Desktop/",
title="Open Text file",
filetypes=(("Text Files", "*.txt"),)
)
pathh.insert(END, tf)
tf = open(tf)
file_cont = tf.read()
txtarea.insert(END, file_cont)
tf.close()
def Draw():
tf = plt.figure(
mode='w',
title ="Draw",
ax = plt.subplots()
plt.subplots_adjust(left=0.3, bottom=0.25)
X, Y = np.loadtxt('data.txt', delimiter=',', unpack=True)
p, = ax.plot(X, Y, color="blue", marker="o")
print(X, Y)
)
tf.config(mode='w')
pathh.insert(END, tf)
data = str(txtarea.get(1.0, END))
tf.write(data)
tf.close()
ws = Tk()
ws.title("PythonGuides")
ws.geometry("400x500")
ws['bg']='#2a636e'
# adding frame
frame = Frame(ws)
frame.pack(pady=20)
# adding scrollbars
ver_sb = Scrollbar(frame, orient=VERTICAL )
ver_sb.pack(side=RIGHT, fill=BOTH)
hor_sb = Scrollbar(frame, orient=HORIZONTAL)
hor_sb.pack(side=BOTTOM, fill=BOTH)
# adding writing space
txtarea = Text(frame, width=40, height=20)
txtarea.pack(side=LEFT)
# binding scrollbar with text area
txtarea.config(yscrollcommand=ver_sb.set)
ver_sb.config(command=txtarea.yview)
txtarea.config(xscrollcommand=hor_sb.set)
hor_sb.config(command=txtarea.xview)
# adding path showing box
pathh = Entry(ws)
pathh.pack(expand=True, fill=X, padx=10)
# adding buttons
Button(
ws,
text="Open File",
command=openFile
).pack(side=LEFT, expand=True, fill=X, padx=20)
Button(
ws,
text="Draw",
command=Draw
).pack(side=LEFT, expand=True, fill=X, padx=20)
Button(
ws,
text="Exit",
command=lambda:ws.destroy()
).pack(side=LEFT, expand=True, fill=X, padx=20, pady=20)
ws.mainloop()
This is the code I try to complete
I tried to find in the Internet but it didn't work.
enter image description here

Related

python) How do I make tkinter appear when a button is pressed?

# import library
import os
import csv
import pandas as pd
import librosa.display
import librosa
import numpy as np
from numpy.fft import fft
from scipy import signal
from scipy.sparse.linalg import svds
from scipy.linalg import hankel
from acoustics.cepstrum import complex_cepstrum
import matplotlib.pyplot as plt
from matplotlib import mlab
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# import GUI
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tksheet import Sheet
from tkinter import filedialog as fd
import tkinter.messagebox as msgbox
# input sr
sr = 2000
ts = 1/sr
style.use('ggplot')
**# tkinter**
main_win = tk.Tk()
main_win.title('program')
main_win.option_add('*font', ('Verdana', 15))
root = tk.Tk()
root.title('Mouse Event')
# mouse event
global mouse_click_no
global mouse_pos
mouse_pos = []
mouse_click_no = 0
mouse_data = []
frame = Frame(main_win)
frame.pack(pady=5)
label = Label(main_win)
label.pack()
# ----------------------------------------------------------------------------------------------------------------------
# csv viewer
def open_file():
global file_name
file_name = fd.askopenfilename(title="Open a File",
filetype=(("csv Files", "*.csv"), ("All Files", "*.*")),
initialdir=r'C:/Users/Ninebell/Desktop/test_data/')
if file_name:
try:
filename = r"{}".format(file_name)
df = pd.read_csv(filename)
except ValueError:
label.config(text="File could not be opened")
except FileNotFoundError:
label.config(text="File Not Found")
disp_csv()
# clear all the previous data in tree
clear_treeview()
tree.pack()
# add new data in treeview widget
tree["column"] = list(df.columns)
tree["show"] = "headings"
# for headings iterate over the columns
for col in tree["column"]:
tree.heading(col, text=col)
# put data in rows
df_rows = df.to_numpy().tolist()
for row in df_rows:
tree.insert("", "end", values=row)
def clear_treeview():
tree.delete(*tree.get_children())
tree = ttk.Treeview(frame)
# display csv file
class disp_csv(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
csv_title=file_name.split('/')[-1]
self.title(csv_title)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.frame = tk.Frame(self)
self.frame.grid_columnconfigure(0, weight=1)
self.frame.grid_rowconfigure(0, weight=1)
self.sheet = Sheet(
self.frame,
data=pd.read_csv(
file_name, # filepath here
).values.tolist(),
)
self.sheet.enable_bindings()
self.frame.grid(row=0, column=0, sticky="nswe")
self.sheet.grid(row=0, column=0, sticky="nswe")
# ----------------------------------------------------------------------------------------------------------------------
**# root tkinter**
def mouse_pos_update(rows):
global mouse_data
mouse_data = rows
treeview.delete(*treeview.get_children())
for i in rows:
treeview.insert('', 'end', values=i)
def save_button():
if len(treeview.get_children()) < 1:
msgbox.showerror('No Data', 'No data available to export')
return False
file_path = fd.asksaveasfilename(title='Save CSV',
filetypes=(("CSV File", "*.csv"), ("All files", "*.*")),
initialdir=r'C:/Users/Ninebell/Desktop/test_data/')
with open(file_path, mode='w', newline='') as myfile:
exp_writer = csv.writer(myfile, delimiter=',')
for i in treeview.get_children():
row = treeview.item(i)['values']
exp_writer.writerow(row)
msgbox.showinfo('Message', 'Export sucessfully')
def load_csv():
mouse_data.clear()
file_path = fd.askopenfilename(title='Open CSV',
filetypes=(("CSV File", "*.csv"), ("All files", "*.*")),
initialdir=r'C:/Users/Ninebell/Desktop/test_data/')
with open(file_path) as myfile:
csv_reader = csv.reader(myfile, delimiter=',')
for i in csv_reader:
mouse_data.append(i)
mouse_pos_update(mouse_data)
msgbox.showinfo('Data imported', 'Your data has be imported to' + os.path.basename(file_path) + 'sucessfully')
txt_browse['text'] = file_path
return None
def clear_button():
treeview.delete(*treeview.get_children())
for item in canvas.get_tk_widget().find_all():
canvas.get_tk_widget().delete(item)
def root_quit():
root.destroy()
# canvas.delete('all')
# ----------------------------------------------------------------------------------------------------------------------
# main_win GUI
menu = tk.Menu(main_win)
menu.config(font=('Verdana', 9))
comm_menu = tk.Menu(menu, tearoff=0)
file_menu = tk.Menu(menu, tearoff=0)
tbf_menu = tk.Menu(menu, tearoff=0)
freq_menu = tk.Menu(menu, tearoff=0)
over_menu = tk.Menu(menu, tearoff=0)
hanm_menu = tk.Menu(menu, tearoff=0)
spec_menu = tk.Menu(menu, tearoff=0)
stft_menu = tk.Menu(menu, tearoff=0)
wave_menu = tk.Menu(menu, tearoff=0)
psd_menu = tk.Menu(menu, tearoff=0)
mfcc_menu = tk.Menu(menu, tearoff=0)
stab_menu = tk.Menu(menu, tearoff=0)
ceps_menu = tk.Menu(menu, tearoff=0)
sine_menu = tk.Menu(menu, tearoff=0)
# telecommunications
comm_menu.add_command(label='Communication')
comm_menu.add_separator()
comm_menu.add_radiobutton(label='Sensor Connection')
comm_menu.add_radiobutton(label='Start')
comm_menu.add_radiobutton(label='Stop')
comm_menu.add_radiobutton(label='Save(csv)')
menu.add_cascade(label='Communication', menu=comm_menu)
# file menu
file_menu.add_command(label='Open File', command=open_file)
# file_menu.add_command(label='Read csv File', command=open_file) # csv 파일 읽기
file_menu.add_separator()
file_menu.add_command(label='Exit', command=quit)
menu.add_cascade(label='File', menu=file_menu)
# overall spectrum
over_menu.add_command(label='Overall Spectrum')
over_menu.add_separator()
over_menu.add_radiobutton(label='x-axis')
over_menu.add_radiobutton(label='y-axis')
over_menu.add_radiobutton(label='z-axis')
menu.add_cascade(label='Overall', menu=over_menu)
# time base frequency menu
tbf_menu.add_command(label='Time Domain', command=disp_time)
tbf_menu.add_separator()
tbf_menu.add_radiobutton(label='x-axis', command=x_time)
tbf_menu.add_radiobutton(label='y-axis', command=y_time)
tbf_menu.add_radiobutton(label='z-axis', command=z_time)
menu.add_cascade(label='Time', menu=tbf_menu)
# frequency menu
freq_menu.add_command(label='Frequency', command=disp_freq)
freq_menu.add_separator()
freq_menu.add_radiobutton(label='x-axis', command=x_freq)
freq_menu.add_radiobutton(label='y-axis', command=y_freq)
freq_menu.add_radiobutton(label='z-axis', command=z_freq)
menu.add_cascade(label='Freq', menu=freq_menu)
# spectrogram 2d
spec_menu.add_command(label='2D Plot', command=disp_spec2d)
spec_menu.add_separator()
spec_menu.add_radiobutton(label='x-axis', command=x_spec2d)
spec_menu.add_radiobutton(label='y-axis', command=y_spec2d)
spec_menu.add_radiobutton(label='z-axis', command=z_spec2d)
spec_menu.add_separator()
# spectrogram 3d
spec_menu.add_command(label='3D Plot', command=disp_spec3d)
spec_menu.add_separator()
spec_menu.add_radiobutton(label='x-axis', command=x_spec3d)
spec_menu.add_radiobutton(label='y-axis', command=y_spec3d)
spec_menu.add_radiobutton(label='z-axis', command=z_spec3d)
menu.add_cascade(label='Spectrogram', menu=spec_menu)
# cepstrum
ceps_menu.add_command(label='Cepstrum', command=disp_ceps)
ceps_menu.add_separator()
# cepstrum time
ceps_menu.add_radiobutton(label='Time x-axis', command=x_ceps)
ceps_menu.add_radiobutton(label='Time y-axis', command=y_ceps)
ceps_menu.add_radiobutton(label='Time z-axis', command=z_ceps)
ceps_menu.add_separator()
# cepstrum frequency
ceps_menu.add_radiobutton(label='Frequency x-axis')
ceps_menu.add_radiobutton(label='Frequency y-axis')
ceps_menu.add_radiobutton(label='Frequency z-axis')
menu.add_cascade(label='Cepstrum', menu=ceps_menu)
# hankel matrix
hanm_menu.add_command(label='Hankel Matrix', command=disp_hank)
hanm_menu.add_separator()
# hankel matrix time
hanm_menu.add_radiobutton(label='Time x-axis', command=x_hank_t)
hanm_menu.add_radiobutton(label='Time y-axis', command=y_hank_t)
hanm_menu.add_radiobutton(label='Time z-axis', command=z_hank_t)
hanm_menu.add_separator()
# hankel matrix frequency
hanm_menu.add_radiobutton(label='Frequency x-axis', command=x_hank_f)
hanm_menu.add_radiobutton(label='Frequency y-axis', command=y_hank_f)
hanm_menu.add_radiobutton(label='Frequency z-axis', command=z_hank_f)
hanm_menu.add_separator()
# hankel matrix spectrum
hanm_menu.add_radiobutton(label='Spectrum x-axis', command=x_hank_s)
hanm_menu.add_radiobutton(label='Spectrum y-axis', command=y_hank_s)
hanm_menu.add_radiobutton(label='Spectrum z-axis', command=z_hank_s)
menu.add_cascade(label='Hankel', menu=hanm_menu)
# wavelet
wave_menu.add_command(label='Wavelet', command=disp_wave)
wave_menu.add_separator()
wave_menu.add_radiobutton(label='x-axis', command=x_wave)
wave_menu.add_radiobutton(label='y-axis', command=y_wave)
wave_menu.add_radiobutton(label='z-axis', command=z_wave)
menu.add_cascade(label='Wavelet', menu=wave_menu)
# STFT
stft_menu.add_command(label='STFT', command=disp_stft)
stft_menu.add_separator()
stft_menu.add_radiobutton(label='x-axis', command=x_stft)
stft_menu.add_radiobutton(label='y-axis', command=y_stft)
stft_menu.add_radiobutton(label='z-axis', command=z_stft)
menu.add_cascade(label='STFT', menu=stft_menu)
# MFCC
mfcc_menu.add_command(label='MFCC', command=disp_mfcc)
mfcc_menu.add_separator()
mfcc_menu.add_radiobutton(label='x-axis', command=x_mfcc)
mfcc_menu.add_radiobutton(label='y-axis', command=y_mfcc)
mfcc_menu.add_radiobutton(label='z-axis', command=z_mfcc)
menu.add_cascade(label='MFCC', menu=mfcc_menu)
# PSD
psd_menu.add_command(label='PSD', command=disp_psd)
psd_menu.add_separator()
psd_menu.add_radiobutton(label='x-axis', command=x_psd)
psd_menu.add_radiobutton(label='y-axis', command=y_psd)
psd_menu.add_radiobutton(label='z-axis', command=z_psd)
menu.add_cascade(label='PSD', menu=psd_menu)
# sine test
sine_menu.add_command(label='Sine Test', command=disp_sine)
sine_menu.add_separator()
sine_menu.add_radiobutton(label='x-axis', command=x_sine)
sine_menu.add_radiobutton(label='y-axis', command=y_sine)
sine_menu.add_radiobutton(label='z-axis', command=z_sine)
menu.add_cascade(label='Sine Test', menu=sine_menu)
# stability
stab_menu.add_command(label='Stability')
stab_menu.add_separator()
stab_menu.add_radiobutton(label='x-axis')
stab_menu.add_radiobutton(label='y-axis')
stab_menu.add_radiobutton(label='z-axis')
menu.add_cascade(label='Stability', menu=stab_menu)
# ----------------------------------------------------------------------------------------------------------------------
# root GUI
frame = Frame(root)
frame.pack(fill='x', padx=5, pady=5)
treeview = tk.ttk.Treeview(frame,
columns=['one', 'two', 'three'],
displaycolumns=['one', 'two', 'three'],
show='headings',
height=10)
treeview.pack(fill='both', padx=5, pady=5)
treeview.column('#1', width=150, anchor='center')
treeview.heading('one', text='index', anchor='center')
treeview.column('#2', width=150, anchor='center')
treeview.heading('two', text='Frequency[Hz]', anchor='center')
treeview.column('#3', width=150, anchor='center')
treeview.heading('three', text='Amplitude[mV/g]', anchor='center')
# browse
browse_frame = LabelFrame(root, text='Open File Dialog')
browse_frame.pack(fill='both', padx=5, pady=5)
txt_browse = Label(browse_frame, text='No File Selected', font=('Verdana', 9, 'bold'))
txt_browse.pack(fill='x', padx=5, pady=5)
# button
button_frame = Frame(root) # bg='white'
button_frame.pack(fill='x', padx=5, pady=5)
btn_exit = Button(button_frame, text='Exit', width=12, command=root_quit)
btn_exit.pack(side='right', padx=5, pady=5)
btn_del = Button(button_frame, text='Clear', width=12, command=clear_button)
btn_del.pack(side='right', padx=5, pady=5)
btn_save = Button(button_frame, text='Save', width=12, command=save_button)
btn_save.pack(side='right', padx=5, pady=5)
btn_load = Button(button_frame, text='Load', width=12, command=load_csv)
btn_load.pack(side='right', padx=5, pady=5)
# ----------------------------------------------------------------------------------------------------------------------
# GUI
root.config(menu=menu)
main_win.config(menu=menu)
main_win.geometry('800x500')
main_win.resizable(False, False)
main_win.mainloop()
This code is a program that displays a graph for each signal when a file is selected. Among them, FFT is set to display the coordinate values in the tree view when the mouse button is pressed. But I want the FFT screen to appear when the button is pressed, but I don't know how to do that part. Should I dig a new class and rewrite it?
for background image in tkinter
from tkinter import *
canv = Canvas(width=200, height=200)
image = PhotoImage(file="./logo.png")
canv.create_image(100, 100, image=image)
canv.grid(row=0, column=1)

How can I return a variable from a function that is opening a file using filedialog after selecting a tkinter button?

All of the tutorials I have seen deomonstrate the tkinter filedialog.askopenfilename function by only using the information collected within the function that is linked to the tkinter button. I can pass information in the function, but I would like to pass variables (filepath, images, etc.) outside the function and have them update variables in my GUI.
I have commented out the location I would like to call the variables in main_gui_setup function below. Any help will be appreciated, as it has been very demoralizing not being able to open a file. If this problem persists, my future as a programmer may be limited to creating tic-tac-toe games or instructional videos for Youtube.
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog, messagebox
from PIL import ImageTk, Image # was import PIL.Image, PIL.ImageTk
import cv2
def main():
root = Tk()
window1 = Window(root, "X-ray Assist", "Give up")
return None
# can't pass by reference in python
class Window():
n = 0
file_path = ""
img1_info = ""
def __init__(self, root, title, message):
self.root = root
self.root.title(title)
#self.root.geometry(geometry)
self.screen_width = root.winfo_screenwidth()
self.screen_height = root.winfo_screenheight()
#self.root.attributes('-topmost', 1)
# SET APP WINDOW SIZE
scr_size_main = self.scr_size() # create instance of scr_size
self.root.geometry("%dx%d+%d+%d" % (self.root_width, self.root_height, self.root_x, self.root_y))
# CREATE MAIN WINDOW GUI
create_gui = self.main_gui_setup()
self.root.mainloop()
pass
def scr_size(self):
'''Reads monitor size and adjusts GUI frame sizes'''
self.root_width = int(self.screen_width*0.52)
self.root_height = int(self.screen_height*0.9)
self.root_x = int(self.screen_width*0.23)
self.root_y = int(self.screen_height*0.02)
self.img_ht_full = int(self.screen_height*0.82)
self.tools_nb_width = int(self.screen_width*0.22)
self.tools_nb_height = int(self.screen_height*0.48)
self.hist_nb_width = int(self.screen_width*0.22)
self.hist_nb_height = int(self.screen_height*0.23)
def open_image(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
self.file_path = filedialog.askopenfilename(initialdir='/', title='Open File',
filetypes=(('tif files', '*.tif'), ('all files', '*.*')))
self.file_path_label = ttk.Label(main_win, text=self.file_path)
self.file_path_label.grid(column=0, row=0, columnspan=1, sticky="nw", padx=(5,0), pady=1)
self.img1_8bit = cv2.imread(self.file_path, 0) #, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img1_8bit_resize = cv2.resize(self.img1_8bit, (self.img_ht_full, self.img_ht_full)) #, interpolation = cv2.INTER_CUBIC)
#self.img1_height, self.img1_width = self.img1_8bit.shape # not resized for screen
#img1_info = text = f"{self.img1_height} {self.img1_8bit.dtype} {self.img1_16bit.dtype}"
#print(self.img1_width, " x ", self.img1_height, " bitdepth = ", self.img1_8bit.dtype)
#img1_info = ttk.Label
#print(f"{self.img1_height} {self.img1_width} {self.img1_8bit.dtype}")
#img1_info.grid(column=3, row=1, columnspan=1, sticky="w", padx=(5,0), pady=1)
#img = io.imread(main_win.filename) #scikit
self.img1_16bit = cv2.imread(self.file_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img_canvas = tk.Canvas(self.root, width=self.img_ht_full, height=self.img_ht_full)
#self.img_canvas.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
#self.img_canvas.image = ImageTk.PhotoImage(image=Image.fromarray(self.img1_8bit_resize))
#self.img_canvas.create_image(0,0, image=self.img_canvas.image, anchor="nw")
# .create_line(x1, y1, x2, y2, fill="color")
#self.img_canvas.create_line((self.img_ht_full/2), 0, (self.img_ht_full/2), (self.img_ht_full), fill="yellow")
#self.img_canvas.create_line(0, (self.img_ht_full/2), (self.img_ht_full), (self.img_ht_full/2), fill="yellow")
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
image_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=self.img_ht_full, height=self.img_ht_full)
image_win.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
toolbar = ttk.Frame(main_win, borderwidth=5) #, width=1100, height=15)
toolbar.grid(column=0, row=0, columnspan=10, rowspan=1, sticky="nw", padx=20)
hist_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=300, height=200)
panel_info = ttk.Label(main_win, text=f"{self.screen_width} x {self.screen_height}")
panel_info.grid(column=5, row=1, columnspan=1, sticky="e", pady=1)
# SCROLL SLIDER AT BOTTOM
slider = ttk.Scrollbar(main_win, orient="horizontal")
slider.grid(column=1, row=13, columnspan=7, padx=5, pady=5, sticky="ew")
#X-RAY AND DETECTOR SETTINGS - will input these from separate class
kv = ttk.Label(main_win, text="125kV")
kv.grid(column=0, row=2, columnspan=1, padx=15, pady=5)
file_path_label = ttk.Label(main_win, text="No image loaded")
file_path_label.grid(column=1, row=1, columnspan=1, sticky="nw", padx=(5,0), pady=1)
# CREATE BUTTONS
open = ttk.Button(toolbar, text="Open", width=10, command=self.open_image)
open.grid(column=0, row=0)
save = ttk.Button(toolbar, text="Save", width=10)
save.grid(column=1, row=0)
b1 = ttk.Button(toolbar, text="1", width=10)
b1.grid(column=2, row=0)
b2 = ttk.Button(toolbar, text="2", width=10)
b2.grid(column=3, row=0)
pass
main()
You aren't thinking of event driven programming correctly. In event driven programming you have callbacks to the functions you defined. Let's look at your code:
def get_path(self):
...
self.path_label = ...
...
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
open = ttk.Button(main_win, text="Open", width=10, command=self.get_path)
open.pack()
# Problematic code:
# main_label = ttk.Label(main_win, self.path_label)
# main_label.pack()
When main_gui_setup is called it creates a frame and a button inside it. When the button is clicked it calls get_path which sets up the path_label variable. The problem that you were facing is that that as soon as you create your button (without waiting for the button to be pressed), you create the label called main_label.
For a simple fix to your problem try this:
def get_path(self):
...
self.file_path = ...
self.path_label = ...
...
def button_callback(self, main_win):
# set up
self.get_path()
# My guess is that you wanted `self.file_path` here instead of `self.path_label`
main_label = ttk.Label(main_win, self.file_path)
main_label.pack()
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
# I am using a lambda and passing in `main_win` because you haven't
# assigned it to `self` using `self.main_win = ...`
open = ttk.Button(main_win, text="Open", width=10, command=lambda: self.button_callback(main_win))
open.pack()
I am still confused by what You are trying to accomplish:
from tkinter import Tk, Button, Label, filedialog
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.open_file_btn = Button(self, text='Open', command=self.open_file)
self.open_file_btn.pack()
self.file_name = None
def open_file(self):
self.file_name = filedialog.askopenfilename()
Label(self, text=self.file_name).pack()
root = MainWindow()
root.mainloop()
I will explain what will happen here! (You can change the .askopenfilename() attributes obviously).
When the program opens the filedialog and You select a file, that file name will now get assigned to self.file_name and that variable can be used anywhere in the class.
also from what I have seen You should learn more about classes and PEP 8

Pyplot and Tkinter - Unwanted Extra Window

My code below creates an unwanted duplicate window when I try to add a window title using plt.figure().canvas.manager.set_window_title("Custom Title").
I've done some research and discovered that I am probably not supposed to be mixing pyplot and tkinter this way as they get confused. However I couldn't really make sense of the proposed solutions, some of which used something called FigureCanvasTkAgg which I don't know about. I want my plot to be freestanding, just as it is when I remove plt.figure().canvas.manager.set_window_title("Custom Title").
How can I refactor my code please to not violate any principles which my current code does and to remove the unwanted window?
import matplotlib.pyplot as plt
import tkinter as tk
import networkx as nx
NUM_ROWS = 5
BOLD_FONT = ("calbri", 12, "bold")
NORMAL_FONT = ("calbri", 12, "normal")
def create_widgets():
for i in range(NUM_ROWS):
key = chr(i + 65)
this_row = widgets[key] = {}
this_row["label"] = tk.Label(root, text=key, font=BOLD_FONT)
this_row["label"].grid(row=i, column=0, padx=5, pady=10)
this_row["factor_field"] = tk.Entry(root, width=60, font=NORMAL_FONT)
this_row["factor_field"].grid(row=i, column=1, padx=5, pady=10)
this_row["target_node_field"] = tk.Entry(
root, width=5, font=NORMAL_FONT)
this_row["target_node_field"].grid(row=i, column=2, padx=5, pady=10)
submit_button = tk.Button(root, text="Submit", command=submit,
font=BOLD_FONT).grid(row=NUM_ROWS + 1, column=0, padx=5, pady=10)
def submit():
plt.close()
G = nx.DiGraph()
edges = []
for key, row in widgets.items():
factor_field_contents = row["factor_field"].get()
target_node_field_contents = row["target_node_field"].get().upper()
if factor_field_contents != "" and target_node_field_contents != "":
edges.append((key, target_node_field_contents))
data[key] = {"factor": factor_field_contents,
"target_node": target_node_field_contents}
G.add_edges_from(edges)
# pos = nx.spring_layout(G, k=1.0, iterations=50)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size=500, node_color="green")
nx.draw_networkx_labels(G, pos, font_color="white")
nx.draw_networkx_edges(
G, pos, connectionstyle='arc3, rad = 0.1', width=2, arrows=True)
plt.figure().canvas.manager.set_window_title("Custom Title")
plt.show()
if __name__ == "__main__":
data = {}
widgets = {}
root = tk.Tk()
root.title("My App")
create_widgets()
root.mainloop()
You said you found a solution in FigureCanvasTkAgg, but you don't understand it. You have to gain that understanding because it is literally the only way (according to my research). My example should get you started in that understanding. To be honest, I don't know anything, at all, about matplotlib. I just read the docs and fulfilled the requirements. It seems to work perfectly at creating a single window.
#import matplotlib.pyplot as plt #remove this, you can't use it anymore
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import tkinter as tk
import networkx as nx
NUM_ROWS = 5
BOLD_FONT = ("calbri", 12, "bold")
NORMAL_FONT = ("calbri", 12, "normal")
def create_widgets():
for i in range(NUM_ROWS):
key = chr(i + 65)
this_row = widgets[key] = {}
this_row["label"] = tk.Label(root, text=key, font=BOLD_FONT)
this_row["label"].grid(row=i, column=0, padx=5, pady=10)
this_row["factor_field"] = tk.Entry(root, width=60, font=NORMAL_FONT)
this_row["factor_field"].grid(row=i, column=1, padx=5, pady=10)
this_row["target_node_field"] = tk.Entry(
root, width=5, font=NORMAL_FONT)
this_row["target_node_field"].grid(row=i, column=2, padx=5, pady=10)
submit_button = tk.Button(root, text="Submit", command=submit,
font=BOLD_FONT).grid(row=NUM_ROWS + 1, column=0, padx=5, pady=10)
#this is your single window
#I'm sure some of this could be made just once and reused
#I'm also sure this could be made more dynamic
#At least you have the multi-window part solved
def plotter():
global plotwin
plotwin = tk.Toplevel(root)
fig = Figure(figsize=(5,5), dpi=100)
fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, plotwin)
canvas._tkcanvas.pack(fill='both', expand=True)
NavigationToolbar2Tk(canvas, plotwin, pack_toolbar=True).update()
def submit():
try:
#if plotter() hasn't been called yet this will throw a NameError
#we simply catch and ignore it
plotwin.destroy()
except NameError as e:
pass
G = nx.DiGraph()
edges = []
for key, row in widgets.items():
factor_field_contents = row["factor_field"].get()
target_node_field_contents = row["target_node_field"].get().upper()
if factor_field_contents != "" and target_node_field_contents != "":
edges.append((key, target_node_field_contents))
data[key] = {"factor": factor_field_contents,
"target_node": target_node_field_contents}
G.add_edges_from(edges)
# pos = nx.spring_layout(G, k=1.0, iterations=50)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size=500, node_color="green")
nx.draw_networkx_labels(G, pos, font_color="white")
nx.draw_networkx_edges(G, pos, connectionstyle='arc3, rad = 0.1', width=2, arrows=True)
#instantiate window
plotter()
if __name__ == "__main__":
data = {}
widgets = {}
root = tk.Tk()
root.title("My App")
create_widgets()
root.mainloop()

How can i print some features in python opencv GUI?

I want to print the mean, height & width of an image in python openCV. Where i used two button (get photo and analysis image) and different GUI,one for getting the photo(def openphoto(): ) and another for printing those features(def feature(): ). But I'm getting error.
N.B. full code is too long.so, i used some part of it.
I've tried it in python openCV.
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title("Dr. Papaya")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print here
print("Mean : ",mean)
print("Heigth : ",heigth)
print("Width : ",width)
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
load = Image.open(fileName)
#calculate the mean
mean=np.mean(load)
#calculate the height & width
height = np.size(load, 0)
width = np.size(load, 1)
render = ImageTk.PhotoImage(load)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
The variables are not in scope when you try to print them. This is an important programming principle so I suggest you read this introduction
You can make the variable global to make the them accessible outside of the function:
def openphoto():
global width, height, mean
[rest of code]

How to print values in GUI from image in python?

I'm new in GUI developing.Here i'hv created two GUI, one for taking photo and another for showing features.so,i'hv used two functions.but i don't know some things.Now i need two kinds of help from you.
1)what is the command for printing float value in GUI(not on console)?
2)How to calculate the value of mean,variance ,s.d. etc from a image and how to pass those values from one function to another function?
import tkinter as tk
from tkinter.filedialog
import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print some features of image e.g. Mean, variance,s.d. Etc.
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
dirPath = " "
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
#this is the image
Photo = Image.open(fileName)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
Okay, I took some more time to look into it.
Concerning the calculation of the values, your previous question did that correct, however the variables needed to be accessible globally. Concerning the displaying of a text, you have to add a tkinter text widget. If you want to add more calculated values, just google for numpy + 'value your want'.
I've taken your code and created a working example, see the code below. Note that I removed some stuff that wasn't neede for the example, so copy the lines you need to your own code. Also check out this reference for the text widget.
Result:
Code:
Note: I created 2 text widgets deliberately, to show 2 ways of implementing multiple texts
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title(" ")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
### create a text widget, place it in window1 and insert the text
width_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
width_txt.grid(column=0, row=0)
width_txt.insert(tk.END, "Width: " + str(width))
height_txt = tk.Text(window1, height=2, width=30, fg="RED", background = "lightgreen", relief="flat")
height_txt.grid(column=0, row=1)
height_txt.insert(tk.END, "Height: " + str(height) + "\nMean: " + str(mean))
window1.geometry("650x510")
window1.configure(background="lightgreen")
def openphoto():
### this line makes the variables accessible everywhere
global width,height, mean
import numpy as np
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
photo = Image.open(fileName)
#### calculate values
height = np.size(photo, 0)
width = np.size(photo, 1)
mean = np.mean(photo)
render = ImageTk.PhotoImage(photo)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()

Categories