def browseSrcFile(self): filename = tkfd.askopenfilename(initialdir=self._convConfigHandler. readMusescoreScoresDefaultFldr(), filetypes=(("XML Files", "*.xml"), ("All Files", "*.*"))) self.endSrcFile.delete(0, END) self.endSrcFile.insert(0, filename)
def dialog(self): c = 0 j = 0 xl = Tk() xl.fileName = filedialog.askopenfilename(filetypes=(("xlsx files", "*.xlsx"), ("xls files", "*.xls"))) workbook = xlrd.open_workbook(xl.fileName) worksheet = workbook.sheet_by_index(0) for i in range(0, worksheet.nrows): if worksheet.cell(i, 0).value != "" and worksheet.cell( i, 1).value != "" and worksheet.cell( i, 2).value != "" and worksheet.cell(i, 3).value != "": self.list1.insert('end', worksheet.cell(i, 0).value) self.list2.insert('end', round(worksheet.cell(i, 1).value, 3)) self.list3.insert('end', round(worksheet.cell(i, 2).value, 3)) self.list4.insert('end', worksheet.cell(i, 3).value) self.list5.insert( 'end', round( worksheet.cell(i, 1).value * worksheet.cell(i, 2).value, 3)) for i in range(0, self.list4.size()): c += self.list4.get(i) j += (self.list4.get(i) * self.list5.get(i)) self.label6['text'] = (f'Quantidade: {int(c)}') self.label7['text'] = (f'M²: {round(j,3)}') c = 0 j = 0
def OnOpen(self, *unused): """Pop up a new dialow window to choose a file, then play the selected file. """ # Create a file dialog opened in the current home directory, where # you can display all kind of files, having as title "Choose a video". video = askopenfilename(initialdir=Path(expanduser("/media")), title="Choose a video", filetypes=(("all files", "*.*"), ("mp4 files", "*.mp4"), ("mov files", "*.mov"))) if (video == ""): self.statusLabel[ "text"] = "No Video Selected\n" + self.statusLabel["text"] return self.clean_all() self.statusLabel[ "text"] = "Opening File: " + video + "\n" + self.statusLabel["text"] setattr(dataSet, "filename", video) self._Play(video) keyFrameThread = Thread(target=thread_getFrames, args=[video]) keyFrameThread.setDaemon(True) keyFrameThread.start()
def OnOpen(self): global filename_store, directory_store, fullname self.OnStop() p = pathlib.Path(os.path.expanduser("~")) fullname = askopenfilename(initialdir=p, title="choose your file", filetypes=(("all files", "*.*"), ("mp4 files", "*.mp4"))) print(fullname) if os.path.isfile(fullname): dirname = os.path.dirname(fullname) filename = os.path.basename(fullname) print(dirname) print(filename) filename_store = str(dirname) + '/' + str(filename) directory_store = str(dirname) print(filename) self.Media = self.Instance.media_new( str(os.path.join(dirname, filename))) self.player.set_media(self.Media) if platform.system() == 'Windows': self.player.set_hwnd(self.GetHandle()) else: self.player.set_xwindow(self.GetHandle()) self.OnPlay() self.volslider.set(self.player.audio_get_volume())
def OnOpen(self): """Pop up a new dialow window to choose a file, then play the selected file. """ # if a file is already running, then stop it. self.OnStop() # Create a file dialog opened in the current home directory, where # you can display all kind of files, having as title "Choose a file". p = pathlib.Path(os.path.expanduser("~")) fullname = askopenfilename(initialdir = p, title = "choose your file",filetypes = (("all files","*.*"),("mp4 files","*.mp4"))) if os.path.isfile(fullname): dirname = os.path.dirname(fullname) filename = os.path.basename(fullname) # Creation self.Media = self.Instance.media_new(str(os.path.join(dirname, filename))) self.player.set_media(self.Media) # Report the title of the file chosen #title = self.player.get_title() # if an error was encountred while retriving the title, then use # filename #if title == -1: # title = filename #self.SetTitle("%s - tkVLCplayer" % title) # set the window id where to render VLC's video output if platform.system() == 'Windows': self.player.set_hwnd(self.GetHandle()) else: self.player.set_xwindow(self.GetHandle()) # this line messes up windows # FIXME: this should be made cross-platform self.OnPlay() # set the volume slider to the current volume #self.volslider.SetValue(self.player.audio_get_volume() / 2) self.volslider.set(self.player.audio_get_volume())
def browse(rootCSV,rootFields,tree,tag,entryText,inDir,logging,fields,file_types): #print('HAST_support.WindfieldBrowse') logging.info(str(datetime.datetime.now())+' HAST_support.browse') #sys.stdout.flush() rootCSV = [] rootFields = {key:''for key, value in fields.items()} #root.WindfieldValid = {} #print('FILE TYPES',*tuple([('type',item.text) for item in next(base.iter('GeneralSettings')).iter('InputFileTypes')])+("all files","*.*")) filename = filedialog.askopenfilename(initialdir = os.path.join(os.getcwd(),tree.find('.//'+inDir).text),title = "Select file",filetypes = file_types)# Gets input csv file from user # Gets field names from input csv file and makes a list try: with open(filename, "r+") as f: reader = csv.reader(f) rootCSV = next(reader) logging.debug(str(datetime.datetime.now())+' File Open: '+filename+' File Fields: '+ str(rootCSV)) rootCSV = list(map(lambda x: x.upper(), rootCSV)) except Exception as e: logging.debug(str(datetime.datetime.now())+' Failed to open input file. Message: '+str(e)) return #Save the input file name and path to the Settings.xml - InputFileName (under this node) tree.getroot().find('.//'+tag).text = filename tree.write('settings.xml') entryText.set(filename) #w.WindfieldLabel.config(text = filename) print(filename,rootFields) return [rootFields, rootCSV]
def load_image(): global image, script_path, log_path, image_count, extension, max_image_count, view_value script_path = os.path.dirname(os.path.realpath(__file__)) log_path = script_path + "\log_folder" file_name = filedialog.askopenfilename( ) #opens up the file_system for user to select a file. returns file path #print(file_name) #prints the entire file path #print(os.path.basename(file_name)) #prints only the actual file name with extension if (not (file_name == "")): #in case user clicked on cancel or cross button if os.path.exists( log_path ): #if the log_folder already exists then delete it and create a new one shutil.rmtree(log_path, ignore_errors=True) #remove the log_folder os.makedirs(log_path) #image_count=0 else: os.makedirs(log_path) #image_count=0 image_count = 0 #as the image was just loaded max_image_count = 0 #as no processing has yet happened on original image view_value = "000" #initializing the values var.set( image_count ) #used to call the callback functions so as to set the proper visibility for the menu options var2.set(view_value) fig.clf() #clear the current canvas fig.add_subplot(111) #makes a 1x1 image plot #some validations in case a 'gif' file or some other non-image file was selected try: name, extension = os.path.basename(file_name).split(".") if (extension == "gif"): raise exception image = scipy.ndimage.imread( file_name, mode='L') #read the image into an numpy.ndarray im = plt.imshow( image, vmin=0, vmax=255 ) #vmin and vmax are required to specify the gray scales. plt.set_cmap('gray') #setting the colormap canvas.draw() #displaying the image on the canvas #increment the image_count and store the current image in the log_folder. #will be required for undo and redo operations. image_count = image_count + 1 var.set(image_count) #save current image in log_folder as 1.extension eg:1.jpg or 1.png current_file = log_path + "\\" + str(image_count) + "." + str( extension) cv2.imwrite( current_file, image ) #cv2.imwrite() is better compared to Image.fromarray() as it doesn't manipulate the image. #selected cv2 for the file write after I found some images getting manipulated by the rescaling required for Image.fromarray(). except Exception as e: messagebox.showerror( title="Can't identify file!!!!", message="This file format is currently not supported")
def browse_button(button, fields): print('HAST_support.browse_button') logging.info(' HAST_support.browse_button') sys.stdout.flush() root.csvFields = [] root.fields = {key: '' for key, value in fields.items()} root.valid = {} #print('FILE TYPES',*tuple([('type',item.text) for item in next(base.iter('GeneralSettings')).iter('InputFileTypes')])+("all files","*.*")) filename = filedialog.askopenfilename( initialdir=os.path.join(os.path.dirname(os.getcwd()), 'input'), title="Select file", filetypes=file_types) # Gets input csv file from user # Gets field names from input csv file and makes a list try: with open(filename, "r+") as f: reader = csv.reader(f) root.csvFields = next(reader) logging.debug(' File Open: ' + filename + ' File Fields: ' + str(root.csvFields)) root.csvFields = list(map(lambda x: x.upper(), root.csvFields)) except Exception as e: logging.debug(' Failed to open input file. Message: ' + str(e)) return #Save the input file name and path to the Settings.xml - InputFileName (under this node) tree.getroot().find('.//InputFileName').text = filename tree.write('settings.xml') FileText.set(filename) print(filename, root.csvFields)
def onBrowse(self): self.filename = askopenfilename(filetypes=(("files", "*.txt"), ("files", "*.*"))) fileSplit = self.filename.split("/") filename = fileSplit[len(fileSplit) - 1].split('.') self.pathEntry.set(self.filename) self.filenameEntry.set(filename[0]) self.fileextensionEntry.set(filename[1])
def OnOpen(self, *unused): self.OnStop() video = askopenfilename(initialdir=Path(expanduser("~")), title="Choose a video", filetypes=(("all files", "*.*"), ("mp4 files", "*.mp4"), ("mov files", "*.mov"))) self._Play(video)
def openPlayList(): #using pickle root.playListFileI = filedialog.askopenfilename( initialdir="/", title="Select your cool music track", filetypes=(("Python File", ".py"), ("Text File", ".txt"))) input = open(root.playListFileI, 'rb') root.playlist = pickle.load(input) input.close()
def load_project_handler(self): file = filedialog.askopenfilename(initialdir=os.path.dirname(__file__), filetypes=(("Project files", "*.dat"), ("All files", "*.*"))) if file == "": return instances = self.program.load_project(file) self.instance_list.delete(0, tk.END) for instance in instances: self.instance_list.insert(tk.END, instance)
def setSourceRom(self): global sourceRoms currRFF = Rom_File_Format[currRomIndex % len(Rom_File_Format)] if currRFF is None or currRFF == "": sourceRoms[currRomIndex].set(askopenfilename()) else: sourceRoms[currRomIndex].set( askopenfilename(filetypes=[("Files", "*." + currRFF)])) if sourceRoms[currRomIndex].get() != "": with open(sourceRoms[currRomIndex].get(), "rb") as inputFile: fileBytes = inputFile.read() currHash = Rom_Hash[currRomIndex % len(Rom_Hash)] if (currHash is not None) and (currHash != ""): fileHash = str(hex( binascii.crc32(fileBytes)))[2:].zfill(8).upper() if currHash.upper() != fileHash: showerror( "Incorrect File", "Incorrect file; CRC32 does not match expected hash.\n\nExpected: " + currHash.upper() + "\nGot: " + fileHash) sourceRoms[currRomIndex].set("")
def OnOpen(self, *unused): """Pop up a new dialow window to choose a file, then play the selected file. """ # if a file is already running, then stop it. self.OnStop() # Create a file dialog opened in the current home directory, where # you can display all kind of files, having as title "Choose a video". video = askopenfilename(initialdir=Path(expanduser("~")), title="Choose a video", filetypes=(("all files", "*.*"), ("mp4 files", "*.mp4"), ("mov files", "*.mov"))) self._Play(video)
def open(self): temp = self.filename self.filename = dialog.askopenfilename(filetypes=[('Text', '*.txt')], title='Open') if self.filename == '': self.filename = temp self.window.title(self.filename + " - Andrea's Notepad") else: data = open(self.filename, 'r+') text = data.read() self.original = text self.text.delete(1.0, 'end-1c') self.text.insert('1.0', text) self.window.title(basename(self.file_ext()) + " - Andrea's Notepad")
def browse_dir(self): backup = self.curr_loc if self.mode.get(): self.curr_loc = dialog.askopenfilename() really = False else: self.curr_loc = dialog.askdirectory() really = True if self.curr_loc: self.contacts_lib = ContactList(self.curr_loc, is_dir=really) self.await_load = True else: self.curr_loc = backup # reverting to previous value
def openFile(): try: root.songAdded = True root.filename = filedialog.askopenfilename( initialdir="/", title="Select your cool music track", filetypes=(("mp3 Music Files", "*.mp3"), ("m4a Music Files", "*.m4a"))) root.playlist.append(root.filename) print(" Added " + root.filename) root.screenMessage.set("Good! Now Press on the Play Button") except: print("Cannot load the music")
def load(): self.shift_activated = False file_name = askopenfilename(defaultextension=".npy") if file_name is None or len(file_name) == 0: return self.layers = np.load(file_name).astype(dtype="int64") self.number_layers, self.number_rows, self.number_columns = self.layers.shape self.entry_rows.delete(0, "end") self.entry_rows.insert(0, self.number_rows) self.entry_columns.delete(0, "end") self.entry_columns.insert(0, self.number_columns) self.label_layer["text"] = "{}/{}".format(self.current_layer + 1, self.number_layers) self.redraw()
def open_and_prep(self): # askopefilename is used to retrieve the file path and file name. self.file_path = filedialog.askopenfilename() def process_open_file(self): # do what you want with the file here. if self.file_path != "": # opens file from file path and prints each line. with open(self.file_path,"r") as testr: for line in testr: print (line) if __name__ == "__main__": # tkinter requires one use of Tk() to start GUI root = tk.Tk() TestApp = ReadFile() # tkinter requires one use of mainloop() to manage the loop and updates of the GUI root.mainloop()
def OnOpen(self): """Pop up a new dialow window to choose a file, then play the selected file. """ # if a file is already running, then stop it. self.OnStop() if self.video: video = expanduser(self.video) self.video = '' else: # Create a file dialog opened in the current home directory, where # you can display all kind of files, having as title "Choose a video". video = askopenfilename(initialdir=Path(expanduser("~")), title="Choose a video", filetypes=(("all files", "*.*"), ("mp4 files", "*.mp4"), ("mov files", "*.mov"))) if isfile(video): # Creation self.Media = self.Instance.media_new(str(video)) self.player.set_media(self.Media) self.parent.title("tkVLCplayer - %s" % (basename(video), )) # set the window id where to render VLC's video output h = self.GetHandle() if _isWindows: self.player.set_hwnd(h) elif _isMacOS: # XXX using the videopanel.winfo_id() handle # causes the video to play in the entire panel, # overwriting the buttons, slider, etc. v = _getNSView(h) if v: self.player.set_nsobject(v) else: self.player.set_xwindow(h) # plays audio, no video else: self.player.set_xwindow(h) # fails on Windows # FIXME: this should be made cross-platform self.OnPlay() # set the volume slider to the current volume #self.volslider.SetValue(self.player.audio_get_volume() / 2) self.volslider.set(self.player.audio_get_volume())
def openPlayFullScreen(self): """Part of open file video from ,FullScreen""" self.OnStop() bring = pathlib.Path(os.path.expanduser("~")) fullname = askopenfilename(initialdir = bring, title = "Choose your file", fileytpes = (("all files", "*.*"),("mp4 files", "*.mp4"))) if os.path.isfile(fullname): print(fullname) Split = os.path.split(fullname) dirname = os.path.dirname(fullname) filename = os.path.basename(fullname) self.Media = self.instance.media_new(str(os.path.join(dirname, filename))) self.player.set_media(self.Media) if platform.system() == 'Windows': self.player.set_hwnd(self.GetHandle()) else: self.player.set_xwindow(self.GetHandle()) self.PlayVlc()
def open_file_meta(self): self.filename_meta = filedialog.askopenfilename() self.filename_meta_label['text'] = ntpath.basename(self.filename_meta)
def open_file(self): self.filename = filedialog.askopenfilename() self.filename_label['text'] = ntpath.basename(self.filename) self.okBtton['state'] = 'normal'
except ImportError: # Python3 import tkinter as tk from tkinter import filedialog ######## # edit input_file_pathname to full file path and name if hardcoding ######## if hardcode: # change this variable if hardcoding input_file_pathname = "*.txt" else: # do not change the below code: runs GUI if not hardcoding root = tk.Tk() root.withdraw() input_file_pathname = filedialog.askopenfilename() # get filename as str ######## # READ, PROCESS DATA: DO NOT CHANGE THE BELOW CODE ######## with open(input_file_pathname) as file: data = file.read() # get all data as str object data = data.split("\n") # convert to list, broken apart at newline char data = data[:-1] # remove empty last item due to trailing newline char # DELETE ILLEGAL CHARS FROM BARCODE STRINGS: data = [item.replace("+", "") for item in data] # "+" removed data = [item.replace(" ", " ") for item in data] # collapse 2 spaces to 1
def OnOpen(self): """Pop up a new dialow window to choose a file, then play the selected file. """ # if a file is already running, then stop it. self.OnStop() # Create a file dialog opened in the current home directory, where # you can display all kind of files, having as title "Choose a file". #p = pathlib.Path(os.path.expanduser("~")) p = pathlib.Path( os.path.expanduser( r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows\show names" )) fullname = askopenfilename(initialdir=p, title="choose your file", filetypes=(("all files", "*.*"), ("mp4 files", "*.mp4"))) #if os.path.isfile(fullname): # print(fullname) # splt = os.path.split(fullname) #dirname = os.path.dirname(fullname) #new addition filename = os.path.basename(fullname) filename = filename[:-4] ##deletes the .txt from the name print(filename) #self.dirname=r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows\that 70s show\season1" ##defining the properties of the show: q1 = """SELECT `episode_table`.`episode_num`, `episode_table`.`episode_time`, `episode_table`.`episode_season` FROM `personal_use`.`episode_table` WHERE `episode_table`.`show_name`='""" + filename + """'""" results = read_query(connection, q1) self.episode_num = results[0][ 0] - 1 ##subracting 1 to match array position of real episode self.episode_season = results[0][2] self.episode_time = results[0][1] self.show_name = filename ##new addition self.dirname = r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows" self.dirname += "\\" self.dirname += filename self.dirname += "\\" self.dirname += "season" self.dirname += str(self.episode_season) ##before updating #self.dirname=r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows\that 70s show\season" #self.dirname+=str(self.episode_season) ##tony ##creating the array of episodes self.mediaList = self.Player.media_list_new() self.videos = os.listdir(self.dirname) for v in self.videos: self.mediaList.add_media( self.Player.media_new(os.path.join(self.dirname, v))) self.listPlayer = self.Player.media_list_player_new() self.listPlayer.set_media_list(self.mediaList) self.Create(self.dirname, self.videos[self.episode_num]) # Creation #self.Media = self.Instance.media_new(str(os.path.join(dirname, filename))) #self.player.set_media(self.Media) # Report the title of the file chosen # title = self.player.get_title() # if an error was encountred while retriving the title, then use # filename # if title == -1: # title = filename # self.SetTitle("%s - tkVLCplayer" % title) # set the window id where to render VLC's video output ##tony: you turned of this so it opens a seperate window #if platform.system() == 'Windows': # self.player.set_hwnd(self.GetHandle()) #else: # self.player.set_xwindow(self.GetHandle()) # this line messes up windows # FIXME: this should be made cross-platform self.OnPlay() # set the volume slider to the current volume # self.volslider.SetValue(self.player.audio_get_volume() / 2) self.volslider.set(self.player.audio_get_volume())
import os import Tkinter as tk from Tkinter import filedialog root = tk.Tk() root.withdraw() root.fileName = filedialog.askopenfilename() root.deiconify() k = input("sdf") print(root.fileName)
def openfile(self): # save user results self.open_name = askopenfilename() # use dialog options here
def chooseFile(): window.sourceFile = filedialog.askopenfilename( parent=window, initialdir="/", title='Please select a directory')
def load(): file_name = askopenfilename(defaultextension=".npy") if file_name is None or len(file_name) == 0: return self.return_queue.put((Graphics2D.MAP_RETURN, file_name))
1 def OnOpen(self): 1 """Pop up a new dialow window to choose a file, then play the selected file. 1 """ 1 # if a file is already running, then stop it. 1 self.OnStop() 1 1 # Create a file dialog opened in the current home directory, where 1 # you can display all kind of files, having as title "Choose a file". 1 p = pathlib.Path(os.path.expanduser("~")) 1 fullname = askopenfilename(initialdir = p, title = "choose your file",filetypes = (("all files","*.*"),("mp4 files","*.mp4"))) 1 if os.path.isfile(fullname): 1 dirname = os.path.dirname(fullname) 1 filename = os.path.basename(fullname) 1 # Creation 1 self.Media = self.Instance.media_new(str(os.path.join(dirname, filename))) 1 self.player.set_media(self.Media) 1 # Report the title of the file chosen 1 #title = self.player.get_title() 1 # if an error was encountred while retriving the title, then use 1 # filename 1 #if title == -1: 1 # title = filename 1 #self.SetTitle("%s - tkVLCplayer" % title) 1 1 # set the window id where to render VLC's video output 1 if platform.system() == 'Windows': 1 self.player.set_hwnd(self.GetHandle()) 1 else: 1 self.player.set_xwindow(self.GetHandle()) # this line messes up windows 1 # FIXME: this should be made cross-platform 1 self.OnPlay() 1 1 # set the volume slider to the current volume 1 #self.volslider.SetValue(self.player.audio_get_volume() / 2) 1 self.volslider.set(self.player.audio_get_volume()) 1 1 def OnPlay(self): 1 """Toggle the status to Play/Pause. 1 If no file is loaded, open the dialog window. 1 """ 1 # check if there is a file to play, otherwise open a 1 # Tk.FileDialog to select a file 1 if not self.player.get_media(): 1 self.OnOpen() 1 else: 1 # Try to launch the media, if this fails display an error message 1 if self.player.play() == -1: 1 self.errorDialog("Unable to play.") 1 1 def GetHandle(self): 1 return self.videopanel.winfo_id() 1 1 #def OnPause(self, evt): 1 def OnPause(self): 1 """Pause the player. 1 """ 2 self.player.pause() 2 2 def OnStop(self): 2 """Stop the player. 2 """ 2 self.player.stop() 2 # reset the time slider 2 self.timeslider.set(0) 2 2 def OnTimer(self): 2 """Update the time slider according to the current movie time. 2 """ 2 if self.player == None: 2 return 2 # since the self.player.get_length can change while playing, 2 # re-set the timeslider to the correct range. 2 length = self.player.get_length() 2 dbl = length * 0.001 2 self.timeslider.config(to=dbl) 2 2 # update the time on the slider 2 tyme = self.player.get_time() 2 if tyme == -1: 2 tyme = 0 2 dbl = tyme * 0.001 2 self.timeslider_last_val = ("%.0f" % dbl) + ".0" 2 # don't want to programatically change slider while user is messing with it. 2 # wait 2 seconds after user lets go of slider 2 if time.time() > (self.timeslider_last_update + 2.0): 2 self.timeslider.set(dbl) 2 2 def scale_sel(self, evt): 2 if self.player == None: 2 return 2 nval = self.scale_var.get() 2 sval = str(nval) 2 if self.timeslider_last_val != sval: 2 # this is a hack. The timer updates the time slider. 2 # This change causes this rtn (the 'slider has changed' rtn) to be invoked. 2 # I can't tell the difference between when the user has manually moved the slider and when 2 # the timer changed the slider. But when the user moves the slider tkinter only notifies 2 # this rtn about once per second and when the slider has quit moving. 2 # Also, the tkinter notification value has no fractional seconds. 2 # The timer update rtn saves off the last update value (rounded to integer seconds) in timeslider_last_val 2 # if the notification time (sval) is the same as the last saved time timeslider_last_val then 2 # we know that this notification is due to the timer changing the slider. 2 # otherwise the notification is due to the user changing the slider. 2 # if the user is changing the slider then I have the timer routine wait for at least 2 # 2 seconds before it starts updating the slider again (so the timer doesn't start fighting with the 2 # user) 2 self.timeslider_last_update = time.time() 2 mval = "%.0f" % (nval * 1000) 2 self.player.set_time(int(mval)) # expects milliseconds 2 2 2 def volume_sel(self, evt): 2 if self.player == None: 2 return 2 volume = self.volume_var.get() 2 if volume > 100: 2 volume = 100 2 if self.player.audio_set_volume(volume) == -1: 2 self.errorDialog("Failed to set volume") 2 2 2 2 def OnToggleVolume(self, evt): 2 """Mute/Unmute according to the audio button. 2 """ 2 is_mute = self.player.audio_get_mute() 2 2 self.player.audio_set_mute(not is_mute) 2 # update the volume slider; 2 # since vlc volume range is in [0, 200], 2 # and our volume slider has range [0, 100], just divide by 2. 2 self.volume_var.set(self.player.audio_get_volume()) 2 2 def OnSetVolume(self): 2 """Set the volume according to the volume sider. 2 """ 2 volume = self.volume_var.get() 2 # vlc.MediaPlayer.audio_set_volume returns 0 if success, -1 otherwise 2 if volume > 100: 2 volume = 100 2 if self.player.audio_set_volume(volume) == -1: 2 self.errorDialog("Failed to set volume") 2 2 def errorDialog(self, errormessage): 2 """Display a simple error dialog. 2 """ 2 Tk.tkMessageBox.showerror(self, 'Error', errormessage) 2 2def Tk_get_root(): 2 if not hasattr(Tk_get_root, "root"): #(1) 2 Tk_get_root.root= Tk.Tk() #initialization call is inside the function 2 return Tk_get_root.root 2 2def _quit(): 2 print("_quit: bye") 2 root = Tk_get_root() 3 root.quit() # stops mainloop 3 root.destroy() # this is necessary on Windows to prevent 3 # Fatal Python Error: PyEval_RestoreThread: NULL tstate 3 os._exit(1) 3 3if __name__ == "__main__": 3 # Create a Tk.App(), which handles the windowing system event loop 3 root = Tk_get_root() 3 root.protocol("WM_DELETE_WINDOW", _quit) 3 3 player = Player(root, title="tkinter vlc") 3 # show the player window centred and run the application 3 root.mainloop() Pyn bindings for libvlcRSSAt