У меня есть функция кнопки, которая использует filedialog.askopenfilename для чтения данных из типов файлов XLS, XLSX, DPT, XY и TXT в DataFrame Pandas. Когда я использую кнопку и открываю что -нибудь, кроме файлов XLS или XLSX, я получаю ошибку, что файл пуст. < /P>
Вот импорт: < /p>
# GUI Imports
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox as mb
# Math / Plotting Imports
import numpy as np
import pandas as pd
from scipy.signal import find_peaks as fp
from scipy.signal import peak_widths as pw
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from BaselineRemoval import BaselineRemoval as BR
# Fancy plotting imports
import plotly.graph_objects as go
from plotly.subplots import make_subplots as sub
import plotly.express as px
import plotly.offline as py
import plotly.io as pio
# Other
import webbrowser
import os
import chardet
pd.options.plotting.backend='plotly'
< /code>
ниже - блок функции: < /p>
def min_max_normalize(array):
"""Normalizes a NumPy array using min-max scaling.
Args:
array: A NumPy array.
Returns:
A normalized NumPy array.
"""
min_val = np.min(array)
max_val = np.max(array)
normalized_array = (array - min_val) / (max_val - min_val)
return normalized_array
def find_index(array, value):
"""Finds the index of the nearest value using NumPy."""
array = np.asarray(array)
idx = np.argmin(np.abs(array - value))
return idx
def open_plot():
#Actual plotting
Upper_index = find_index(data.iloc[:,0],float(Upper_x))
Lower_index = find_index(data.iloc[:,0],float(Lower_x))
x = data.iloc[:,0].values
intensity = data.iloc[:,1].values
bg_data = BR(intensity).ZhangFit() # Removes background
Norm_bg_data = min_max_normalize(bg_data)
peaks,properties = fp(bg_data, prominence=20) # Detects peaks at indices
widths, width_heights, left_ips,right_ips = pw(bg_data, peaks, rel_height=0.5) # Calculates FWHM
filtered_peaks = peaks[(peaks>=Lower_index) & (peaks
Затем я запускаю ячейку ниже, чтобы открыть графический интерфейс Tkinter: < /p>
# Open File Window
base = tk.Tk()
base.title('Analysis Tool')
base.geometry('1000x500')
# Hacking into the main frame
main_frame = tk.Frame(base)
main_frame.pack(pady=10)
title_label = ttk.Label(master = base, text = 'Select your data', font = 'Comic_sans 24 bold')
title_label.pack(pady=10)
open_file_button = ttk.Button(base, text = 'Choose file',command=open_file)
open_file_button.pack(pady=10)
output_string = tk.StringVar()
output_label = ttk.Label(
base,
text = 'Choose file...',
textvariable= output_string)
output_label.pack(pady=5)
# Additional section
file_section = ttk.Frame(base)
entry1_float = tk.DoubleVar()
entry2_float = tk.DoubleVar()
advice_label = ttk.Label(file_section, text = 'Leave the fields as is for the full spectrum.')
advice_label.pack()
entry1_label = ttk.Label(file_section, text = 'Please type your desired starting x value')
entry1 = ttk.Entry(file_section, textvariable= entry1_float)
entry2_label = ttk.Label(file_section, text = 'Please type your desired ending x value')
entry2 = ttk.Entry(file_section, textvariable= entry2_float)
entry1_label.pack()
entry1.pack()
entry2_label.pack()
entry2.insert(0, '1000')
entry2.pack()
submit_bounds_button = ttk.Button(file_section, text='Submit Bounds', command=get_bounds)
submit_bounds_button.pack(pady=10)
output_string2 = tk.StringVar()
output_label2 = ttk.Label(
file_section,
text = '',
textvariable=output_string2
)
output_label2.pack(pady=5)
open_plots_in_new_window = ttk.Button(file_section, text = 'Open in browser', command=open_plot)
open_plots_in_new_window.pack(pady=10)
output_string3 = tk.StringVar()
output_label3 = ttk.Label(
file_section,
text='',
textvariable=output_string3
)
output_label3.pack(pady=5)
# base.after(60000, lambda: base.destroy())
warning_label = ttk.Label(file_section, text = 'CLOSE THIS WINDOW BEFORE STOPPING CODE!', font='Chiller 24 italic')
warning_label.pack(pady=5)
base.mainloop()
< /code>
Затем я получаю эту ошибку: < /p>
pandas.errors.EmptyDataError: No columns to parse from file
< /code>
Я сделал отдельный блок, чтобы проверить сами инструменты Pandas.read_csv и pandas.read_excel, которые работают как задумано. Таким образом, что -то отличается от включения его в функцию, хранящуюся в кнопке, в результате чего он прочитал любой другой тип файла в качестве пустого. < /P>
Upper_x = 10000
Lower_x = 0
file = filedialog.askopenfilename(filetypes=[("DPT files", "*.dpt"), ("Text files", "*.txt"), ("Excel files", "*.xlsx *.xls"),("XY files", "*.xy")])
try:
data = pd.read_csv(file, header='infer', sep='[ \t]',engine='python')
except:
data = pd.read_excel(file)
#Actual plotting
Upper_index = find_index(data.iloc[:,0],float(Upper_x))
Lower_index = find_index(data.iloc[:,0],float(Lower_x))
x = data.iloc[:,0].values
intensity = data.iloc[:,1].values
bg_data = BR(intensity).ZhangFit() # Removes background
Norm_bg_data = min_max_normalize(bg_data)
peaks,properties = fp(bg_data, prominence=20) # Detects peaks and returns indices
widths, width_heights, left_ips,right_ips = pw(bg_data, peaks, rel_height=0.5) # Calculates FWHM
filtered_peaks = peaks[(peaks>=Lower_index) & (peaks
Подробнее здесь: [url]https://stackoverflow.com/questions/79671347/interactive-plotly-plots-with-file-reader-not-reading-correctly-through-button-f[/url]
У меня есть функция кнопки, которая использует filedialog.askopenfilename для чтения данных из типов файлов XLS, XLSX, DPT, XY и TXT в DataFrame Pandas. Когда я использую кнопку и открываю что -нибудь, кроме файлов XLS или XLSX, я получаю ошибку, что файл пуст. < /P> Вот импорт: < /p> [code]# GUI Imports import tkinter as tk from tkinter import ttk from tkinter import filedialog from tkinter import messagebox as mb # Math / Plotting Imports import numpy as np import pandas as pd from scipy.signal import find_peaks as fp from scipy.signal import peak_widths as pw import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from BaselineRemoval import BaselineRemoval as BR # Fancy plotting imports import plotly.graph_objects as go from plotly.subplots import make_subplots as sub import plotly.express as px import plotly.offline as py import plotly.io as pio # Other import webbrowser import os import chardet pd.options.plotting.backend='plotly'
< /code> ниже - блок функции: < /p> def min_max_normalize(array): """Normalizes a NumPy array using min-max scaling.
def find_index(array, value): """Finds the index of the nearest value using NumPy.""" array = np.asarray(array) idx = np.argmin(np.abs(array - value)) return idx
peaks,properties = fp(bg_data, prominence=20) # Detects peaks at indices widths, width_heights, left_ips,right_ips = pw(bg_data, peaks, rel_height=0.5) # Calculates FWHM filtered_peaks = peaks[(peaks>=Lower_index) & (peaks Затем я запускаю ячейку ниже, чтобы открыть графический интерфейс Tkinter: < /p> # Open File Window
base = tk.Tk() base.title('Analysis Tool') base.geometry('1000x500')
# Hacking into the main frame main_frame = tk.Frame(base) main_frame.pack(pady=10) title_label = ttk.Label(master = base, text = 'Select your data', font = 'Comic_sans 24 bold') title_label.pack(pady=10) open_file_button = ttk.Button(base, text = 'Choose file',command=open_file) open_file_button.pack(pady=10)
# Additional section file_section = ttk.Frame(base) entry1_float = tk.DoubleVar() entry2_float = tk.DoubleVar() advice_label = ttk.Label(file_section, text = 'Leave the fields as is for the full spectrum.') advice_label.pack() entry1_label = ttk.Label(file_section, text = 'Please type your desired starting x value') entry1 = ttk.Entry(file_section, textvariable= entry1_float) entry2_label = ttk.Label(file_section, text = 'Please type your desired ending x value') entry2 = ttk.Entry(file_section, textvariable= entry2_float) entry1_label.pack() entry1.pack() entry2_label.pack() entry2.insert(0, '1000') entry2.pack() submit_bounds_button = ttk.Button(file_section, text='Submit Bounds', command=get_bounds) submit_bounds_button.pack(pady=10)
warning_label = ttk.Label(file_section, text = 'CLOSE THIS WINDOW BEFORE STOPPING CODE!', font='Chiller 24 italic') warning_label.pack(pady=5) base.mainloop() < /code> Затем я получаю эту ошибку: < /p> pandas.errors.EmptyDataError: No columns to parse from file < /code> Я сделал отдельный блок, чтобы проверить сами инструменты Pandas.read_csv и pandas.read_excel, которые работают как задумано. Таким образом, что -то отличается от включения его в функцию, хранящуюся в кнопке, в результате чего он прочитал любой другой тип файла в качестве пустого. < /P> Upper_x = 10000 Lower_x = 0
Я пытаюсь создать интерактивный график с помощью Plotly, но он продолжает печатать два графика вместо одного.
Вот код, который я использую, и результат, который я получил :
# Initialize the position of the bar with the first start value...
Я пытаюсь построить региональную карту с реками и контурами озер с помощью карты. Это привлекает несуществующую часть реки внутри озера. См. Изображение Bellow:
Код следующим образом:
import cartopy.crs as ccrsimport cartopy.feature as cfeature...
Я пытаюсь построить региональную карту с реками и контурами озер с помощью карты. Это привлекает несуществующую часть реки внутри озера. См. Изображение Bellow:
Код следующим образом:
import cartopy.crs as ccrsimport cartopy.feature as cfeature...
Внутри виджета есть кнопка
Button(intent: AnAppIntent()) {
// Button's label.
}
// It seems this modifier does not add any value.
.invalidatableContent()
подключен к AppIntent.
struct AnAppIntent: AppIntent {
static var title:...