Новый для Tkinter. Я был в этом в течение нескольких дней. Я пытаюсь передать путь к файлу в формате Mp4 (полученный с помощью askopenfilename и кнопки) в другой кадр (где я беру первый кадр и отображаю его, чтобы пользователь мог выбрать область интереса).
ОБНОВЛЕНО! МИНИМАЛЬНЫЙ, ДЕЙСТВУЮЩИЙ ПРИМЕР: ВЫПОЛНЯЯ ЭТОТ КОД, ВЫБРАННЫЙ ФИЛИАЛ НЕ ОТОБРАЖАЕТСЯ НА ВТОРОЙ ФРЕЙМЕ (ПРОБЛЕМА):
LARGE_FONT=("Verdana",12)
import tkinter as tk
from tkinter import filedialog
from tkinter import *
filename = ''
class HRDetectorApp(tk.Tk): #in brackets, what the class inherits
def __init__(self,*args,**kwargs): #this will always load when we run the program. self is implied args = unlimited vars. kwargs are keywords arguments (dictionaries)
tk.Tk.__init__(self,*args,**kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True) #pack into top, fill into entire top space, and expand will expand into the whole window. fill into the area you packed.
container.grid_rowconfigure(0, weight=1) #min size zero, weight is priority
container.grid_columnconfigure(0,weight=1)
self.frames = {}
self.shared_data = {"filename": tk.StringVar()}
for F in (StartPage, SelectROIPage):
frame = F(container,self)
self.frames[F] = frame
frame.grid(row=0,column=0, sticky="nsew") #sticky = alignment + stretch, north south east west
self.show_frame(StartPage)
self.title("Heart Rate Detection")
def show_frame(self,cont):
frame=self.frames[cont]
frame.tkraise()
def get_page(self, page_class):
return self.frames[page_class]
def openFile():
root = tk.Tk()
global filename
filename = filedialog.askopenfilename(title="Select an Mp4 Video", filetypes =(("Mp4 Files", "*.mp4"),))
root.update_idletasks()
print(filename)
class StartPage(tk.Frame):
def __init__(self,parent,controller):
self.controller = controller
#global filename
#filename = ""
tk.Frame.__init__(self,parent)
label = tk.Label(self,text="Start Page", font=LARGE_FONT)
label.pack(pady=10,padx=10)
self.filename = tk.StringVar()
chooseFileButton = tk.Button(self,text="Upload a Video",command=openFile)
chooseFileButton.pack()
goButton = tk.Button(self,text ="Click me after you've uploaded a video!", command = lambda: controller.show_frame(SelectROIPage))
goButton.pack()
class SelectROIPage(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self,text="Select a Region of Interest (R.O.I)", font=LARGE_FONT)
label.pack(pady=10,padx=10)
label = tk.Label(self, text = "selected file : " + filename)
label.pack()
app = HRDetectorApp()
app.mainloop()
Как воспроизвести?
- Нажмите «Загрузить видео» и выберите файл MP4.
- Нажмите «Нажмите меня после загрузки видео»
Для некоторых причина, переменная не обновляется после вызова askopenfilename. Я пытался использовать глобальные переменные, используя root .update, ничего не помогло (см. Мои попытки закомментированы)
Любая помощь очень ценится, спасибо!
ОРИГИНАЛЬНЫЙ КОД: спасибо за ваши предложения по его упрощению :)
LARGE_FONT=("Verdana",12)
import tkinter as tk
from tkinter import filedialog
from tkinter import *
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.widgets import RectangleSelector
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import cv2
import numpy as np
import sys
import time
from scipy import signal
import scipy.signal as signal
import selectinwindow
class HRDetectorApp(tk.Tk): #in brackets, what the class inherits
def __init__(self,*args,**kwargs): #this will always load when we run the program. self is implied args = unlimited vars. kwargs are keywords arguments (dictionaries)
tk.Tk.__init__(self,*args,**kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True) #pack into top, fill into entire top space, and expand will expand into the whole window. fill into the area you packed.
container.grid_rowconfigure(0, weight=1) #min size zero, weight is priority
container.grid_columnconfigure(0,weight=1)
self.frames = {}
self.shared_data = {"filename": tk.StringVar()}
for F in (StartPage, SelectROIPage):
frame = F(container,self)
self.frames[F] = frame
frame.grid(row=0,column=0, sticky="nsew") #sticky = alignment + stretch, north south east west
self.show_frame(StartPage)
self.title("Heart Rate Detection")
def show_frame(self,cont):
frame=self.frames[cont]
frame.tkraise()
def get_page(self, page_class):
return self.frames[page_class]
#
#def openFile():
# root = tk.Tk()
# global filename
# root.filename = filedialog.askopenfilename(title="Select an Mp4 Video", filetypes =(("Mp4 Files", "*.mp4"),))
# filename = root.filename
# root.update_idletasks()
# #name = root.filename
#
# print(filename)
class StartPage(tk.Frame):
def __init__(self,parent,controller):
self.controller = controller
# global filename
# filename = ""
tk.Frame.__init__(self,parent)
label = tk.Label(self,text="Start Page", font=LARGE_FONT)
label.pack(pady=10,padx=10)
self.filename = tk.StringVar()
chooseFileButton = tk.Button(self,text="Upload a Video",command=self.openFile)
chooseFileButton.pack()
goButton = tk.Button(self,text ="Click me after you've uploaded a video!", command = lambda: controller.show_frame(SelectROIPage))
goButton.pack()
def openFile(self):
#root = tk.Tk()
#global filename
#root.filename = filedialog.askopenfilename(title="Select an Mp4 Video", filetypes =(("Mp4 Files", "*.mp4"),))
# filename = root.filename
self.filename.set(filedialog.askopenfilename(title="Select an Mp4 Video", filetypes =(("Mp4 Files", "*.mp4"),)))
#root.update()
#if filename == "":
#root.after(1000,openFile(self))
#name = root.filename
print(self.filename.get())
**code to use rectangle selector for selecting ROI**
class SelectROIPage(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
self.controller = controller
startpg = self.controller.get_page(StartPage)
file = startpg.filename.get() **THIS IS NOT UPDATING**
label = tk.Label(self,text="Select a Region of Interest (R.O.I)", font=LARGE_FONT)
label.pack(pady=10,padx=10)
#file=filename
**code to read image and display it (confirmed no errors here!)**
app = HRDetectorApp()
app.mainloop()