I have made a "program" that creates a mikrotik config file, I am currently just running it straight as a python program, but I'd like to move it toward having a GUI, I am trying to use Tkinter for this but it is really confusing me, I was hoping someone here would be able to help me out, I don't want to show the full code because it's quite long, but I'll outline what it currently does.
mr= open(input("File Name: "), "w+")
DHCP_Range = input("DHCP Range: ")
PBX_IP = input("PBX IP: ")
DG = input("Default Gateway: ")
Network_IP = input("Network IP: ")
Currently that is the main thing the rest is mostly just the config being printed out and those variables get places throughout it as necessary.
What I want the GUI to do is ask me for the variables and then have an OK box down the bottom that then runs the rest of the script, if you guys are able to give me helpful resources or even build an example I'd be forever grateful as I'm really struggling with it.
Do you mean like having a tkinter messagebox?
If you want to prompt and ask the user its ok, you can add 2 types of codes ->
from tkinter import messagebox
messagebox.askokcancel('Ok Cancel', 'Are You sure?')
messagebox.askyesno('Yes|No', 'Do you want to proceed?')
Here is a resource that you can checkout:
[1]: https://pythonguides.com/python-tkinter-messagebox/
Related
I am hoping someone can help me.
Basically, I have an arbitrary script, in this script, there are many functions and after each function is executed, print() is executed as well to give me an update. I'm using the Pysimplegui library for GUI, and was wondering if someone can help or explain what I can do to show the print output in the GUI
There are a few ways to do this that are in the documentation, here is one way.
import PySimpleGUI as sg
# This is the normal print that comes with simple GUI
sg.Print('Re-routing the stdout', do_not_reroute_stdout=False)
# this is clobbering the print command, and replacing it with sg's Print()
print = sg.Print
# this will now output to the sg display.
print('This is a normal print that has been re-routed.')
Here is the example output
Whenever you are going to use any library, first read the docs.
I am sure you can find your answer.
https://pysimplegui.readthedocs.io/en/latest/
I am relatively new to python and have to write a code for a "Countdown" based game; the program would basically ask the user for a word, see whether it is located in a file of words, and if it isn't print (directly after the word input by the user) "is invalid".
Here is the portion of code relative to this (I would supply the whole thing but I'm actually in France so it's in French...)
And here is what I see on my screen now, relative to what I have been asked for.
I'm also new to this forum so apologies in advance if this post isn't as polished as others!
Many thanks in advance to anyone willing to help, it's greatly appreciated!
You could do something like this:
def wordcheck(word):
if ...:
return word + " is valid"
else:
return word + " is invalid"
print("Proposed word: {0} ".format(wordcheck(input())))
Where "if ..." is you checking if the word is valid
So, Python is a general purpose language, and just as any other language, it has nothing to do with the I/O capabilities - those are up to the ambient you are running it.
he built-in "input" has fixed behavior - and unless you change the terminal behavior for things like "turning echo off", it will just proceed to the next terminal line when the user press the return key.
Under Windows, the usual way to get more control over the terminal is to use the msvcrt library - not you'd have to build your own "input" function based on the several character-reading functions there. Actually if you are on Windows, that is likely the way your teacher wants you to follow.
On any other platform, the high-level way to do it is to use the curses library.
I hope you can find your way from there.
I'm trying to learn how to build a web browser bot as half learning half project for someone else and I've hit a snag.
The site I'm using as guide has:
def main():
pass
Which he claims keeps the shell window open do he can run various functions like get x,y cords of the mouse position and take screen shots.
However when I run my code exactly as he has it in the guide it immediately opens and closes.
What I don't want is something like, "make it so pressing enter closes shell instead", what needs to happen is the window stays open so I can enter various functions.
What am I doing wrong? Am I suppose to just import the code in a different shell and run the functions outside it?
The code:
import os
import time
import ImageGrab
x_pad = 0
y_pad = 61
def screenGrab():
box = (x_pad,y_pad,x_pad+1919,y_pad+970)
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) + '.png','PNG')
def main():
pass
if __name__ == '__main__':
main()
The guide is: http://code.tutsplus.com/tutorials/how-to-build-a-python-bot-that-can-play-web-games--active-11117
You have three ways:
Start the intepreter with the -i option, as suggested by Ulrich in the comments:
python -i my-script.py
This way, the interpreter will be left open as soon as your script finishes execution and a prompt will be shown.
Use pdb. This is often used for debugging, and has a different interface than the usual Python prompt. If you're not familiar with it, it might not be the best option in your case. Replace pass with these two lines:
import pdb
pdb.set_trace()
Use code. This will give you an interface much more similar to the usual Python shell and can be an alternative to pdb if you're not familiar with it:
import code
code.interact()
By the way, you were not doing anything wrong per se. The pass statement is not meant to "halt Python and start a prompt", it's just needed as a filler for functions or loops with an empty body.
I have an Entry in a python program in which i want my users to enter a URL. my first task is to check whether user entered a value or not. I'v used the following code but it's not working as expected.
my entry name is txtUrl
if(txtUrl.get() == ""):
tkMessageBox.showerror("Error", "please enter a url")
if user entered a url then show the next window
else:
webCrawl=Tk()
#and other widgets in it
This is how I create the txtUrl widget
self.txtUrl=Entry(self)
self.txtUrl["width"]=60
self.txtUrl.grid(row = 0, column = 1, sticky = EW)
I also tried to use this line
self.txtUrl["textvariable"]=content
and tried to get the value as below and check for its emptiness but it didn't work too
if(content.get()==""):
tkMessageBox.showerror("Error","please enter a url")
someone please let me know how to check for it. I'm trying to do a similar task done by a required field validator in asp.net
There is not enough information in your question to answer. You say something isn't working but you don't say what that means. The specific line of code you say isn't working looks syntactically correct. So, unless you can be more specific about what behavior or errors you are getting, there's no way we can help.
You have another crucial error in your code which may be contributing to the problem. Specifically, the line where you do else: webCrawl=Tk(). You should never need to create more than a single instance of Tk during the course of a program. If all you're doing is creating more windows, create an instance of Toplevel.
(I edited the whole question to be more clear)
Hello,
I have never had any affairs with Python GUI libraries. I know there are plenty and well documented, but as I need only one single snippet, I would dislike to dive deep into documentations to seek for a way how to do it. If I am going to write a GUI program, I surely would do that, but this is needed only as a few lines for my ad hoc script.
What would be the easiest and the most straightforward way for me (GUI noob) to write in Python following piece of code? Less lines = more happiness.
Grab a JPEG picture by filename.
Display it's thumbnail.
Below the thumbnail display a textfield so the user can type in a caption.
Wait until user hits ENTER key on his/her keyboard. In that case, close and return the input.
...or wait until user hits DELETE key. In that case, close and return an information about the decision (to delete the picture).
Dependencies or Linux-only solutions are okay. I need to run this on Xubuntu machine. Any code snippets, please? I believe this is a matter of 5 minutes for someone skilled in Python GUI field. I would need to study loads of library docs. Thank you!
Below is a minimal python script that more or less fits the spec.
It requires python2 and pyqt4 packages to be installed, and it won't work with python3 (although it could quite easily be adapted to do so if necessary).
If the user types in a valid caption and presses enter, the script will return with status code 0 and print the caption to stdout; otherwise, if the user enters an invalid caption (empty or whitespace only), or simply closes the dialog without doing anything, the script will return with status code 1 and print nothing.
example bash usage:
$ CAPTION=$(python imgviewer.py image.jpg)
$ [ $? -eq 0 ] && echo $CAPTION
imgviewer.py:
import sys, os
from PyQt4 import QtGui, QtCore
class Dialog(QtGui.QDialog):
def __init__(self, path):
QtGui.QDialog.__init__(self)
self.viewer = QtGui.QLabel(self)
self.viewer.setMinimumSize(QtCore.QSize(400, 400))
self.viewer.setScaledContents(True)
self.viewer.setPixmap(QtGui.QPixmap(path))
self.editor = QtGui.QLineEdit(self)
self.editor.returnPressed.connect(self.handleReturnPressed)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.viewer)
layout.addWidget(self.editor)
def handleReturnPressed(self):
if self.editor.text().simplified().isEmpty():
self.reject()
else:
self.accept()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
args = app.arguments()[1:]
if len(args) == 1:
dialog = Dialog(args[0])
if dialog.exec_() == QtGui.QDialog.Accepted:
print dialog.editor.text().simplified().toLocal8Bit().data()
sys.exit(0)
else:
print 'ERROR: wrong number of arguments'
sys.exit(1)
There are several good GUI libraries for Python. The "standard" library that comes built-in with python is tkinter:http://wiki.python.org/moin/TkInter. Some says that wxPython is much more powerful and straightforward: http://www.wxpython.org/.
I think that you can start with wxPython, they have many many tutorials and examples you can dig into (just run the DEMO).
They have an example called "ImageBrowser" which might be a very good starting point.
Regarding the communication between the different apps, you can use "pipes" and "redirections" to communicate. But if everything is written in python, I think this is the wrong way to go, you can show the image form within your python script and get the result internally.