[英]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.
其中,FFT被设置为在按下鼠标按钮时在树形视图中显示坐标值。 But I want the FFT screen to appear when the button is pressed, but I don't know how to do that part.
但是我希望在按下按钮时出现 FFT 屏幕,但我不知道该怎么做。 Should I dig a new class and rewrite it?
我应该挖一个新的 class 并重写它吗?
for background image in tkinter用于 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.