pyqt5 treeview refresh with nas server - python

i have create a simple file namager with pyqt5 and QTreeView().
W΅hen my path is local folder ...creating ,deleting etc from the app it show it in treeview without problem , example path
C:\Users\USER\Documents\projects\someFile
but when the path is nas server is not show changes example path
\my-ip-add\web\data\someFile
edit: i made create files and folder to update when change made, now trying for delete and drag and drop
in both cases files/folder are deleted ,created . the issue is in nas is not update treeview in delete function and in drag n drop
import os
import sys
from PyQt5.QtWidgets import QTreeView, QFileSystemModel, QApplication, QMenu, QAbstractItemView,QAction, QFileDialog, QMessageBox
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import options
import shutil
class Tree(QTreeView):
def __init__(self, path):
QTreeView.__init__(self)
self.settings = options.Settings()
self.model_base = QFileSystemModel()
self.path = path
self.model_base.setRootPath(self.path)
self.setModel(self.model_base)
self.setRootIndex(self.model_base.index(self.path))
self.model_base.setReadOnly(False)
self.setSelectionMode(self.SingleSelection)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.open_menu)
self.doubleClicked.connect(self.OpenFileFromTree)
def dragEnterEvent(self, event):
m = event.mimeData()
if m.hasUrls():
for url in m.urls():
if url.isLocalFile():
event.accept()
return
event.ignore()
def dropEvent(self, event):
if event.source():
QTreeView.dropEvent(self, event)
else:
ix = self.indexAt(event.pos())
if not self.model().isDir(ix):
ix = ix.parent()
pathDir = self.model().filePath(ix)
m = event.mimeData()
if m.hasUrls():
urlLocals = [url for url in m.urls() if url.isLocalFile()]
accepted = False
for urlLocal in urlLocals:
path = urlLocal.toLocalFile()
info = QFileInfo(path)
n_path = QDir(pathDir).filePath(info.fileName())
o_path = info.absoluteFilePath()
if n_path == o_path:
continue
if info.isDir():
QDir().rename(o_path, n_path)
else:
qfile = QFile(o_path)
if QFile(n_path).exists():
n_path += "(copy)"
qfile.rename(n_path)
accepted = True
if accepted:
event.acceptProposedAction()
def open_menu(self):
menu = QMenu()
NewFolderAction = QAction('New Folder', self)
NewFolderAction.triggered.connect(self.create_folder)
# new file action
NewFileAction = QAction('New File', self)
NewFileAction.triggered.connect(self.create_file)
# delete action
DeleteAction = QAction('Delete', self)
DeleteAction.triggered.connect(self.delete_file)
# rename action
RenameAction = QAction('Rename', self)
menu.addAction(NewFolderAction)
menu.addAction(NewFileAction)
menu.addAction(DeleteAction)
menu.exec_(QCursor.pos())
def delete_file(self):
# create QMessageBox to ask if the user is sure to delete the file
box = QMessageBox()
box.setIcon(QMessageBox.Question)
box.setWindowTitle('ΠΡΟΣΟΧΗ!')
box.setText('Are you sure?')
box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
buttonY = box.button(QMessageBox.Yes)
buttonY.setText('Yes')
buttonN = box.button(QMessageBox.No)
buttonN.setText('Cancel')
box.exec_()
if box.clickedButton() == buttonY:
try:
index = self.currentIndex()
file_path = self.model_base.filePath(index)
if os.path.isfile(file_path):
os.remove(file_path)
self.model_base.setRootPath(file_path)
else:
# os.rmdir(file_path)
shutil.rmtree(file_path, ignore_errors=True)
self.model_base.setRootPath(file_path)
except Exception as e:
options.SaveLogs('delete_file' + str(e))
pass
elif box.clickedButton() == buttonN:
pass
def create_file(self):
index = self.currentIndex()
file_path = self.model_base.filePath(index)
file_name = QFileDialog.getSaveFileName(self, "Επιλογή αρχείου", file_path)
# self.model_base.setRootPath(file_path)
if file_name[0]:
with open(file_name[0], 'w') as f:
new_folder_index = self.model_base.index(file_name[0])
# Expand the tree view to the new folder
self.expand(new_folder_index)
self.setCurrentIndex(new_folder_index)
pass
# create a function to open a dialog to create a new folder
def create_folder(self):
try:
global new_folder_path
index = self.currentIndex()
if not self.model_base.isDir(index):
index = index.parent()
# Get the path of the current index
path = self.model_base.filePath(index)
# Create a new folder
new_folder = QFileDialog.getSaveFileName(self, "Select Folder", path)
if new_folder[1]:
new_folder_path = os.path.join(path, new_folder[0])
QtCore.QDir().mkdir(new_folder_path)
# Get the index of the new folder
new_folder_index = self.model_base.index(new_folder_path)
# Expand the tree view to the new folder
self.expand(new_folder_index)
self.setCurrentIndex(new_folder_index)
except Exception as e:
options.SaveLogs('create_folder ' + str(e))
pass
def OpenFileFromTree(self):
try:
index = self.currentIndex()
file_path = self.model_base.filePath(index)
self.model_base.setRootPath(file_path)
p = file_path.replace("//", "\\\\").replace("/", "\\")
os.startfile(p)
except Exception as e:
options.SaveLogs('OpenFileFromTree ' + str(e))
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
tree = Tree(r"\\my-ip\web\data\someFile")
tree.show()
sys.exit(app.exec_())

Related

How to open default browser download location with QFileDialog in Python?

I would like that QFileDialog in PyQt5 opens in default browser dowload location. I have this code, which opens last used location, because of '' empty third parameter. How can I read this information in Windows and Linux?
def selectfile_Dialog(self, event=None):
fname, _ = QtWidgets.QFileDialog.getOpenFileName(
self, 'Open File', '', 'Binary executable (*.exe)', None)
# sender is object that sends the signal
sender = self.sender()
# write the selected file name into that QLineEdit widget 'list1_lineEdit'
sender.setText(fname)
Here's a possible solution:
import sys
import webbrowser
import os
import winreg
from PyQt5.Qt import * # noqa
def get_download_path():
if os.name == 'nt':
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
location = winreg.QueryValueEx(key, downloads_guid)[0]
return location
else:
return os.path.join(os.path.expanduser('~'), 'downloads')
def main():
app = QApplication(sys.argv)
fname, _ = QFileDialog.getOpenFileName(
None, 'Open File', get_download_path(), 'Binary executable (*.exe)', None
)
sys.exit(app.exec_())
if __name__ == "__main__":
main()

PyQt 5 QTableWidget.cellClicked Signal Not Working

I am trying to make a simple files app (or, file explorer app) and I am using the QTableWidget to Display the files and directories. When the user clicks an directory, I want the program to jump to that directory. I have used the QTableWidget.cellClicked signal, and it does not currently work.
The signal part:
self.filesTable.connect(print)#self.updateUiCellClick)
Added print instead of self.updateUiCellClick for debugging purposes.
Code (probably you do not need this):
#!/usr/bin/python3
print('i Import Modules')
print(' | Import sys')
import sys
print(' | Import PyQt5.QtCore')
from PyQt5.QtCore import *
print(' | Import PyQt5.QtGui')
from PyQt5.QtGui import *
print(' | Import PyQt5.QtWidgets')
from PyQt5.QtWidgets import * # PyQt5 Support
print(' | Import os')
import os
print(' | Import subprocess.Popen') # For backward-compatibility
from subprocess import Popen, PIPE
print(' | Done')
print('i Define class Form')
class root(QMainWindow):
def __init__(self, parent=None):
'''self.__init__ - Initializes QMainWindow'''
print(' self.__init__ - Initializes QMainWindow')
super(root, self).__init__(parent)
# Create Variables
self.currentPath = '/'
os.chdir(self.currentPath)
self.currentItems = os.listdir()
self.currentItemsLsProcess = Popen(['ls','-l'], stdout=PIPE, stderr=PIPE)
self.currentItemsLsProcessResult = self.currentItemsLsProcess.communicate()
if self.currentItemsLsProcessResult[1].decode('utf-8'):
QMessageBox.warning(self,'Files - ls -l Error','ls -l responded with non-blank stderr.Error is shown here:<br><code>{}</code><br><hr><br>Error LsStderr (e-lsstderr)<br><hr><br>If you want to support the team, go to the GitHub Repository.'.format(self.currentItemsLsProcessResult[1].decode('utf-8')))
self.currentItemsLs = self.currentItemsLsProcessResult[0].decode('utf-8').split('\n')[1:-1]
# Create Table Widget
self.filesTable = QTableWidget()
# Init Table Widget
self.filesTable.clear()
self.filesTable.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
self.filesTable.setRowCount(len(self.currentItems))
self.filesTable.setColumnCount(4)
self.filesTable.setHorizontalHeaderLabels(['Name','TimeStamp','Type','ls -l'])
# self.filesTable.setReadOnly(1)
# Create & Add Items
self.itemWidgets = [[],[],[],[]]
for i in range(len(self.currentItems)):
self.itemWidgets[0].append(QTableWidgetItem(self.currentItems[i]))
self.filesTable.setItem(i,0,self.itemWidgets[0][-1])
self.itemWidgets[3].append(QTableWidgetItem(self.currentItemsLs[i]))
self.filesTable.setItem(i,3,self.itemWidgets[3][-1])
# Init Widgets
# Align Widgets to root
self.setCentralWidget(self.filesTable)
# Signals-and-Slots
print('i Set self title')
self.setWindowTitle('{}'.format(self.currentPath))
def updateUi(self):
'''self.updateUi - None'''
os.chdir(self.currentPath)
self.currentItems = os.listdir()
self.currentItemsLsProcess = Popen(['ls','-l'], stdout=PIPE, stderr=PIPE)
self.currentItemsLsProcessResult = self.currentItemsLsProcess.communicate()
if self.currentItemsLsProcessResult[1].decode('utf-8'):
QMessageBox.warning(self,'Files - ls -l Error','ls -l responded with non-blank stderr.Error is shown here:<br><code>{}</code><br><hr><br>Error LsStderr (e-lsstderr)<br><hr><br>If you want to support the team, go to the GitHub Repository.'.format(self.currentItemsLsProcessResult[1].decode('utf-8')))
self.currentItemsLs = self.currentItemsLsProcessResult[0].decode('utf-8').split('\n')[1:-1]
self.filesTable.clear()
self.filesTable.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.filesTable.setRowCount(len(self.currentItems))
self.filesTable.setColumnCount(4)
self.filesTable.setHorizontalHeaderLabels(['Name','TimeStamp','Type','ls -l'])
self.itemWidgets = [[],[],[],[]]
for i in range(len(self.currentItems)):
self.itemWidgets[0].append(QTableWidgetItem(self.currentItems[i]))
self.filesTable.setItem(i,0,self.itemWidgets[0][-1])
self.filesTable..connect(print)#self.updateUiCellClick)
self.itemWidgets[3].append(QTableWidgetItem(self.currentItemsLs[i]))
self.filesTable.setItem(i,3,self.itemWidgets[3][-1])
self.filesTable.resizeColumnsToContents()
self.setWindowTitle('{}'.format(self.currentPath))
def updateUiCellClick(self, row, column):
'''self.updateUiCellClick - None'''
print('self.updateUiCellClick - None')
self.currentpath += self.itemWidgets[0][row].text+'/'
self.updateUi()
print(' | Done')
if __name__ == '__main__':
print('i Execute instance')
app = QApplication(sys.argv)
root = root()
root.show()
app.exec_()
print(' | Done')
The connection should be as follows
self.filesTable.cellClicked.connect(self.updateUiCellClick)
^^^^^^^^^^^
signal
In addition to this it is not necessary to create the connection every time you fill in the table, it is enough when you create it.
If you look at code you see that many parts are repeating, which is not necessary, I take the boldness to make improvements to your code as the verification of path and reduce the code.
import sys
import os
from subprocess import Popen, PIPE
from PyQt5.QtWidgets import *
class Root(QMainWindow):
def __init__(self, parent=None):
print(' self.__init__ - Initializes QMainWindow')
QMainWindow.__init__(self, parent)
# Create Table Widget
self.filesTable = QTableWidget()
self.filesTable.cellClicked.connect(self.updateUiCellClick)
# Init Table Widget
self.filesTable.clear()
self.filesTable.setSizeAdjustPolicy(QTableWidget.AdjustToContents)
self.filesTable.setColumnCount(4)
self.filesTable.setHorizontalHeaderLabels(['Name', 'TimeStamp', 'Type', 'ls -l'])
# Init Widgets
self.setCentralWidget(self.filesTable)
self.populate_table("/")
def populate_table(self, path):
# Verify that it is a directory.
if not os.path.isdir(path):
return
os.chdir(path)
current_items = os.listdir()
currentItemsLsProcess = Popen(['ls', '-l'], stdout=PIPE, stderr=PIPE)
currentItemsLsProcessResult = currentItemsLsProcess.communicate()
if currentItemsLsProcessResult[1].decode('utf-8'):
QMessageBox.warning(self, 'Files - ls -l Error',
'ls -l responded with non-blank stderr.Error is shown here:'
'<br><code>{}</code><br><hr><br>Error LsStderr (e-lsstderr)<br>'
'<hr><br>If you want to support the team, go to the '
'GitHub Repository.'.format(
currentItemsLsProcessResult[1].decode('utf-8')))
return
self.filesTable.clear()
currentItemsLs = currentItemsLsProcessResult[0].decode('utf-8').split('\n')[1:-1]
self.filesTable.setRowCount(len(current_items))
for i, values in enumerate(zip(current_items, currentItemsLs)):
name, ls = values
self.filesTable.setItem(i, 0, QTableWidgetItem(name))
self.filesTable.setItem(i, 3, QTableWidgetItem(ls))
self.setWindowTitle('{}'.format(path))
def updateUiCellClick(self, row, _):
path = os.path.join(os.getcwd(), self.filesTable.item(row, 0).text())
self.populate_table(path)
if __name__ == '__main__':
print('i Execute instance')
app = QApplication(sys.argv)
root = Root()
root.show()
status = app.exec_()
print(' | Done')
sys.exit(status)

Running a function when a widget window is brought to the front?

I'm building a gui front-end for a project I've been working on, and I'm having trouble figuring out this specific aspect of PyQT. Long ago there was a post that I had that I think would've solved the problem but I can't quite find it.
Regardless, I have the following files, main.py and playlistcreator.py respectively:
(main.py)
import getpass
import playlistcreator
import os
import sys
import sip
sip.setapi('QString', 2)
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
# Window class
class Window(QWidget):
def __init__(self): # constructor for Window (passes "self" -aka Window- to __init__ to initialize it)
super(Window, self).__init__() # inherits from QMainWindow
self.setGeometry(50, 50, 300, 150) # Set window dimensions
self.setWindowTitle("Google Music Playlist Transfer") # Set window title
self.setWindowIcon(QIcon('gmusic.png')) # Set window icon
self.login = QWidget() # login widget ("front page")
self.processing = QWidget() # on successful login - being processing data
self.file_inputs = QWidget() # after processing, ask user where they would like to store data
# call functions
self.loginUI()
self.processingUI()
self.file_inputsUI()
# create stacked widget and add layouts to stack
self.Stack = QStackedWidget(self)
self.Stack.addWidget(self.login)
self.Stack.addWidget(self.processing)
self.Stack.addWidget(self.file_inputs)
main_box = QHBoxLayout(self)
main_box.addWidget(self.Stack)
self.setLayout(main_box)
self.show()
def loginUI(self):
# Set email field
self.email = QLineEdit()
self.email.setMaxLength(110)
self.email.setAlignment(Qt.AlignLeft)
# Set password field
self.pwd = QLineEdit()
self.pwd.setAlignment(Qt.AlignLeft)
self.pwd.setEchoMode(QLineEdit.Password)
# Form layout
form_layout = QFormLayout()
form_layout.addRow("Email: ", self.email)
form_layout.addRow("Password: ", self.pwd)
# Login button
self.login_btn = QPushButton("Login", self) # login button
self.login_btn.clicked.connect(self.process_login) # tell button what to do
self.login_btn.resize(self.login_btn.sizeHint())
# Quit button
self.quit_btn = QPushButton("Exit", self) # exit button
self.quit_btn.clicked.connect(self.close_application) # tell button what to do
# Error label layout
self.error_layout = QHBoxLayout()
# Button box layout
button_box = QHBoxLayout()
button_box.addStretch(1)
button_box.addWidget(self.login_btn)
button_box.addWidget(self.quit_btn)
# input layout (main layout for "home")
input_box = QVBoxLayout()
input_box.addLayout(self.error_layout)
input_box.addLayout(form_layout)
input_box.addLayout(button_box)
self.login.setLayout(input_box)
def processingUI(self):
# setup layout
layout = QHBoxLayout()
# alert user that we're grabbing track data
self.progress_label = QLabel("Grabbing tracks from Google Music. . .")
self.progress_label.setStyleSheet("color: rgb(0, 100, 0);")
layout.addWidget(self.progress_label)
# Get users list of "thumbs up" tracks from Google Music
# set layout
favorite_tracks = self.get_tracks
self.processing.setLayout(layout)
def file_inputsUI(self):
layout = QFormLayout()
# Set text field for directory
self.dir_textbox = QTextEdit(self)
# Add textbox to layout
layout.addRow("Music Directory: ", self.dir_textbox)
self.file_inputs.setLayout(layout)
def close_application(self):
confirm = QMessageBox.question(self, 'Exit Confirmation',
"Are you sure you want to exit?",
QMessageBox.Yes | QMessageBox.No)
if confirm == QMessageBox.Yes:
sys.exit()
else:
pass
def process_login(self):
email_input = str(self.email.text())
pwd_input = str(self.pwd.text())
login_successful = playlistcreator.login(email_input, pwd_input)
if login_successful:
self.Stack.setCurrentIndex(1)
else:
self.error_label = QLabel("Please check your email/password!")
self.error_label.setStyleSheet("color: rgb(255, 0, 0);")
self.error_layout.addWidget(self.error_label)
def get_tracks(self):
tracks = playlistcreator.get_favorite_tracks()
print("You have ", len(tracks), " favorite tracks!")
return tracks
# def open_dir_dialog(self):
# directory = QFileDialog.getExistingDirectory(self, 'Select USB Drive Location')
# self.myTextBox.setText(fileName)
def main():
# Create an PyQT5 application object.
app = QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
# # Input Music Directory
# music_dir = input("Please put the path to your music folder: ")
# list_of_paths = playlistcreator.findmp3(music_dir, favorite_tracks)
# # Input playlist file save location
# playlist_path = input("Where would you like to save the playlist?: ")
# playlist_name = input("What would you like to name the playlist? ")
# playlist_name += ".m3u8"
# # Testing appending file extension to string
# playlistcreator.addtoplaylist(list_of_paths, playlist_path, playlist_name)
# playlistcreator.logout()
main()
(playlistcreator.py)
import os
from gmusicapi import Mobileclient
from mutagen.easyid3 import EasyID3
api = Mobileclient()
songCount = 0
favorite_files_path = []
logged_in = False
def login(email, password):
library = []
if "#" not in email:
email += "#gmail.com"
logged_in = api.login(email, password, Mobileclient.FROM_MAC_ADDRESS)
return logged_in
def get_favorite_tracks():
print("Getting songs from Google Music. . .")
library = api.get_all_songs()
print("There are", len(library), "items in your music library")
good_songs = [song for song in library if song['rating'] == '5']
print("You have", len(good_songs), "favorite tracks!")
return good_songs
def logout():
api.logout()
def findmp3(rootFolder, favoriteTracks):
print("Searching for favorite tracks. . .")
for directory, subdirectory, files in os.walk(rootFolder, topdown=False): # for all files in directory
global songCount
global favorite_files_path
for mp3 in files: # for files in
if mp3.endswith(".mp3"): # if file ends with .mp3
file_path = os.path.join(directory, mp3) # concatenate to create full path
try:
file_tags = EasyID3(file_path) # grab file tags from mp3 file
except:
file_tags = EasyID3() # create tags if none are found
file_tags.save(file_path) # save file to have new tags
if "title" in file_tags:
fileTitle = file_tags["title"][0] # TIT2 = corresponding tag in mutagen for song title
else:
fileTitle = "None"
if "artist" in file_tags:
fileArtist = file_tags["artist"][0] # TPE = corresponding tag in mutagen for artist
else:
fileArtist = "None"
if "album" in file_tags:
fileAlbum = file_tags["album"][0] # TALB = corresponding tag in mutagen for album
else:
fileAlbum = "None"
for track in favoriteTracks:
gMusicTitle = track["title"]
gMusicArtist = track["artist"]
gMusicAlbum = track["album"]
if fileTitle in gMusicTitle and fileArtist in gMusicArtist and fileAlbum in gMusicAlbum: # if file tags (artist, album, title) match gMusic tags
songCount += 1
if songCount == 1:
print("Found 1 song")
else:
print("Found", songCount, "songs") # print updated count of found tracks
favorite_files_path.append(file_path) # add all found files to a list (via their paths)
break # break out of "for track in favorite tracks"
return favorite_files_path
def addtoplaylist(paths, playlist_path, playlist_name):
# Open file (or create if it does not exist)
# change to given directory
try:
os.chdir(playlist_path)
except Exception as err:
print(err)
# open file - if it does not exist, create it
with open(playlist_name, 'a+', encoding="UTF-8") as playlistFile:
print("Adding tracks...", end="")
for track in paths:
print(".", end="")
playlistFile.write(track + '\n')
playlistFile.close()
The problem I've been running into is when the user logs in they hit the processingUI window (which states that the program is grabbing all their tracks from Google) but it doesn't actually seem to be running the get_tracks() method (which is what actually gets the user's tracks from Google), as the program hangs there and doesn't do anything.
I've tested the program without a GUI using straight command line, and it works flawlessly, but I'm not sure what the issue is with the GUI - do I need to thread the execution to start when the proper "window" is brought to the front?

PyQt application closes immediately after start

I'm trying make an exe application from my scripts using py2exe. The problem is that if I run it by doubleclicking on exe file, it closes immediately after open. If I run it from cmd, it works perfect.
I've tried to make a table global but it did not helped. I've already tried to keep the reference - no effect.
Here is the code of GUI in case it helps:
from PyQt4.QtGui import QTableWidget, QTableWidgetItem,QApplication
import sys
from PyQt4.QtGui import *
import os
from meteo import mesiac,den
class MyTable(QTableWidget):
def __init__(self, data, *args):
QTableWidget.__init__(self, *args)
self.data = data
self.setmydata()
self.resizeColumnsToContents()
self.resizeRowsToContents()
def setmydata(self):
horHeaders = []
for n, key in enumerate(['max teplota','min teplota','max vlhkost','min vlhkost','max tlak',
'min tlak','avg teplota','avg vlhkost','avg tlak']):
horHeaders.append(key)
for m, item in enumerate(self.data[key]):
newitem = QTableWidgetItem(str(item))
self.setItem(m, n, newitem)
self.setHorizontalHeaderLabels(horHeaders)
vertical_headers = ['{}.'.format(x+1) for x in xrange(len(self.data.values()[0])-1)]+['Mesiac:']
self.setVerticalHeaderLabels(vertical_headers)
self.setWindowTitle('Meteo')
def show_table():
global table
table = MyTable(data, len(data.values()[0]), len(data.keys()))
table.setFixedHeight(len(data.values()[0])*20)
table.setFixedWidth(len(data.keys())*95)
table.show()
return table
if __name__ == '__main__':
data = {}
os.system("mode con: cols=100 lines=40")
filenames = next(os.walk('mesiac'))[2]
list_of_den = []
for filename in filenames:
list_of_den.append(den(filename,filename[:-4]))
m = mesiac(list_of_den)
for den in list_of_den:
for n,attr in enumerate(['max teplota','min teplota','max vlhkost','min vlhkost','max tlak',
'min tlak','avg teplota','avg vlhkost','avg tlak']):
try:
data[attr].append(den.to_list()[n])
except:
data[attr]=[den.to_list()[n]]
m_list = m.to_list()
for n,attr in enumerate(['max teplota','min teplota','max vlhkost','min vlhkost','max tlak',
'min tlak','avg teplota','avg vlhkost','avg tlak']):
try:
data[attr].append(m_list[n])
except:
data[attr]=[m_list[n]]
app = QApplication(sys.argv)
t = show_table()
sys.exit(app.exec_())
And for sure - here is a setup.py file:
from distutils.core import setup
import py2exe
options ={"py2exe":{"includes":["sip","PyQt4.QtGui","PyQt4.QtCore","meteo"],"dll_excludes": ["MSVCP90.dll", "HID.DLL", "w9xpopen.exe"]}}
setup(window=['table.py'],options=options)
How to make it visible?

How do I have my wxpython window stay open or re-open after I enter my text?

Also, why does this not save to library.txt? It does not close properly either (mac). I wan't for this program to be able to run on windows OS primarily. Here is my spaghetti code:
http://pastebin.com/NLx77zHu
import wx
f = open('library.txt', "a")
class ooer(wx.Frame):
def __init__(self, parent, title):
super(ooer, self).__init__(parent, title=title, size=(390, 125))
box=wx.TextEntryDialog(None, "Dewey Number, Author Name", "Library", "ex. 822 SHA")
if box.ShowModal()==wx.ID_OK:
answer=box.GetValue()
f.write(answer)
f.close
if __name__=='__main__':
app=wx.App()
ooer(None, title='Add Books To Library')
app.MainLoop()
The following code creates a frame that stays open until you close it by clicking the X.
It has seperate TextCtrl's for each line of entry and a button to click when you want to save.
It calls a seperate function to do the saving to file.
import wx
from wx.lib import sized_controls
class AddBooksFrame(sized_controls.SizedFrame):
def __init__(self, *args, **kwargs):
super(AddBooksFrame, self).__init__(*args, **kwargs)
pane = self.GetContentsPane()
pane_form = sized_controls.SizedPanel(pane)
pane_form.SetSizerType('form')
pane_form.SetSizerProps(align='center')
label = wx.StaticText(pane_form, label='Dewey Number')
label.SetSizerProps(halign='right', valign='center')
self.ctrl_dewey_no = wx.TextCtrl(pane_form, size=((200, -1)))
label = wx.StaticText(pane_form, label='Author Name')
label.SetSizerProps(halign='right', valign='center')
self.ctrl_author_name = wx.TextCtrl(pane_form, size=((200, -1)))
pane_btns = sized_controls.SizedPanel(pane)
pane_btns.SetSizerType('horizontal')
pane_btns.SetSizerProps(halign='right')
btn_save = wx.Button(pane_btns, wx.ID_SAVE)
btn_save.Bind(wx.EVT_BUTTON, self.on_btn_save)
self.Fit()
def on_btn_save(self, event):
dewey_no = self.ctrl_dewey_no.GetValue()
author_name = self.ctrl_author_name.GetValue()
try:
add_book_to_file(dewey_no, author_name)
self.ctrl_dewey_no.Clear()
self.ctrl_author_name.Clear()
except ValueError as exception:
dialog = wx.MessageDialog(
self, str(exception), 'Entry error',
wx.ICON_ERROR | wx.OK | wx.CENTER)
dialog.ShowModal()
dialog.Destroy()
def add_book_to_file(dewey_no, author_name):
if not dewey_no:
raise ValueError('Dewey Number must not be empty')
if not author_name:
raise ValueError('Author Name must not be empty')
with open('library.txt', "a") as library_txt:
library_txt.write('{}, {}\n'.format(dewey_no, author_name))
if __name__ == '__main__':
wxapp = wx.App(False)
main_app_frame = AddBooksFrame(
None, title='Add Books To Library', style=wx.DEFAULT_DIALOG_STYLE)
main_app_frame.Show()
wxapp.MainLoop()

Categories

Resources