I'm trying to work on a GUI done in pyqt. I'm trying to create a pop-up window has a textbox where a user can type/set the user's id (1-99) and then click an 'ok' button to set it and close the window.
This is what I have so far.
def viewProfile(self)
profBox = QMessageBox()
QMessageBox.about(self, 'Profile', "///Text box where can type User ID:// ",
QMessageBox.Ok)
I am not sure how to generate the textbox.
Also, if I want to display the integer value or string of a variable in my message window /box do I just leave it out of quotation marks but include it? What's the syntax for it?
Thank you!
You want to use a QInputDialog. This has a bunch of static methods which generate a complete dialog, and return the selected integer when the user clicks OK. This means you don't need to worry about creating a dialog object, adding widgets and buttons, etc.
So you would want to call:
parent_window = self #probably..., depends on your code
minimum_value = 1
maximum_value = 99
default_value = 1
title = "Profile"
message = "Select your user ID"
user_id, ok = QInputDialog.getInt(parent_window, title, message, default_value, minimum_value, maximum_value)
When the QInputDialog line of code runs, a dialog will be presented to the user. When the user clicks OK or Cancel, the entered user_ID will be placed in user_id and ok will be a boolean value that indicates whether the OK button was clicked (True if the OK button was clicked, False if the cancel button was clicked)
If you want to place an integer in the message, you could do something like:
message = "Select your user ID. An integer I want you to know about is %d. I hope you find that useful."%my_integer
But that is really a Python string formatting question, which you should research separately. In short, in my example you can display one string. How long, that string is, is up to you (it can be multiple lines, have new line characters, etc)
You should use QDialog. That way you can customize it the way you want (add textbox, button...)
Take a look at my answer here, basically it's log-in dialog created in QTDesigner, but you can create it with code since it's way more simplier
Related
I have a code snippet which runs perfectly. In some cases, I need user input, but there are also cases where user input is not necessary and code functions without it perfectly.
So, in that cases I create with conditional a flow where entry box widget is created and destroyed after value is get() by script. But I cannot make code to wait until to say stops(pauses) when the user has given input value then continues to run.
code is below;
varSheetname_GS = ''
if varsoundTitle_usernameHeroContainer == 'FloatingBlueRecords' or varsoundTitle_usernameHeroContainer == 'DayDoseOfHouse':
varSheetname_GS = varsoundTitle_usernameHeroContainer
else:
# look for sheetname as an input value entered by user
new_sheetname_entryBox=tk.Entry(canvas2,width=30).pack()
new_sheetname_entryBox.focus()
var_new_sheetName =new_sheetname_entryBox.get()
new_sheetname_entryBox.destroy()
varSheetname_GS = var_new_sheetName #input("Enter the sheetname in (GooSheets):")
I have looked for so_01 and so_02 which are related to topic but was not able to implement in my situation. So, anyone who would guide me towards that answers would be great from yourside.
Thanks ahead!
You can use the wait_window method to wait until the entry widget has been destroyed. You can then bind the return key to destroy the window. If the entry is associated with a StringVar, you can get the value after the widget has been destroyed.
The solution might look something like this:
entry_var = tk.StringVar()
new_sheetname_entryBox=tk.Entry(canvas2,width=30, textvariable=entry_var)
new_sheetname_entryBox.pack()
new_sheetname_entryBox.bind("<Return>", lambda event: new_sheetname_entryBox.destroy())
new_sheetname_entryBox.focus_set()
# wait for the entry widget to be deleted...
new_sheetname_entryBox.wait_window()
# save the value
varSheetname_GS = entry_var.get()
In the pythonista app for iOS I'm trying to check if a textfield in my ui has any numbers in it when I press on a button. When I use the same code on a string it works. When I use the code for textfield within a button's action it doesn't work. Please help? Here's what my code is like:
import ui
import console
def contains_digits(d):
for char in d:
if char.isdigit():
return True
return False
test='test3'
print(contains_digits(test)) #this works - it prints TRUE!
#below always prints failed even though it should print whatever is in the textfield?!
def button_pushed(sender):
if contains_digits(textfield1):
print(textfield1)
print('failed')
v=ui.load_view()
textfield1 = str(v['textfield1'].text)
v.present('fullscreen')
You’re setting the variable textfield to the field’s text before any text can be entered into the textfield1 TextField.
It will work if you just set textfield1 to v['textfield1'] and then get the .text out of it in your button_pushed function.
def button_pushed(sender):
if contains_digits(textfield1.text):
print(textfield1.text)
return
print('failed')
v=ui.load_view()
textfield1 = v['textfield1']
v.present('fullscreen')
This works because, instead of setting the text to what is in the field at startup, it waits until you have received notification that the field has been changed (assuming that is when button_pushed is called).
However, the best way to do this is to use the sender variable that button_pushed receives. Assuming you’ve set the TextField up so that textfield1.action is the button_pushed function, sender should be the TextField, so that you can do:
def button_pushed(sender):
if contains_digits(sender.text):
print(sender.text)
return
print('failed')
(Note that the way button_pushed is set up in your code, it will always print failed even if it also prints the semi-numeric text. You also need a return after the successful printing.)
I am aware of two ways to set a TextField to call a function (or method) as its action in Pythonista. The easiest is probably to set it within your code.
v=ui.load_view()
textfield1 = v['textfield1']
textfield1.action = button_pushed
v.present('fullscreen')
The other method is to set it within the UI file. When you have the TextField selected in the UI editor, and are looking at the settings for the TextField (as I write this, the “i” button in the upper right brings up the settings), the very bottom setting is “CUSTOM ATTRIBUTES”. Set the custom attributes to:
{'action':button_pushed}
Once you make either of these changes, then whenever the text field has finished editing (for example, by pressing “return” or by moving the focus to another field), that action will be called. Of course, if you do this and it turns out to be the behavior you want, you may wish to change the name of the function from button_pushed to something more descriptive of when or why the function is called.
You may also wish to change the name of the TextField from its default of “textfield1” to something more descriptive of its purpose as well, so as to make your code easier to follow once you have multiple fields to work with.
I'm trying to create variables at the top of my script so that users can manipulate it's values without needing to go down into the code. E.g.
# Airports
FROM = "Leeds Bradford"
TO = "Antalya"
...//Later in code
depart_from = driver.find_element_by_id("departure-airport-input")
depart_from.clear()
depart_from.send_keys(FROM)
depart_from = driver.find_element_by_id("destination-airport-input")
depart_from.clear()
depart_from.send_keys(TO)
One thing I can't seem to get my head around is where a user may have a choice between selecting one radio button or the other. At the moment it's rigid where I say click this type of radio button.
return_flight = driver.find_element_by_id('return-flight-selector').click()
But I want the user to decide which radio button to select between the above and below:
one_flight = driver.find_element_by_id('oneway-flight-selector').click()
Is there a way I can do this? I want to assign a number to a radio button, so that all the user needs to do is change a number to get either one or the other? Like for example having a variable call FLIGHT_TYPE = ? ? is either "0" meaning select the return_flight radio button, or "1" meaning select the one_flight radio button.
Sure make a boolean variable and call it, for instance, ONE_WAY. Then, depending on it's value decide which item to click:
ONE_WAY = True
if ONE_WAY:
driver.find_element_by_id('oneway-flight-selector').click()
else:
driver.find_element_by_id('return-flight-selector').click()
I've got a problem with Entry widget while making a copy of Windows Calc.
I have made buttons like in windows calc and I also bind the keyboard 1234567890 + - / * % buttons, to make the same things as the calc buttons.
The mainly problem was that I wanted the Entry to store only numbers and let user input only numbers... but after searching many topics about validatecommand and also looking at windows calc I decided that validatecommand isn't the thing I need - I don't know how to make it validate every character the user inputs to the entry box and after making the keyboard binds, when I am in entrybox and press "1" to write the number it does it two times, because the keyboard event binding inserts the "1" to the entry box too.
So, the thing I want to make is to make entry widget work like the Windows Calc.exe entry box.
The windows calc entry box doesn't let you insert any other character then numbers and also doesn't let you to put your cursor into the entry box...,
it looks like this:
-entrybox is disabled BUT it looks like ENABLED
-numbers and operations can be made by calc buttons or by keyboard buttons
I tried getting this effect by disabling the entry widget at start, and making all buttons functions like that:
-enable the entry widget
-insert the number (the widget must be in enabled? or normal? (don't remember the name) state to let you insert something to it)
-disable the entry widget
It works like I want... but it doesn't look like I want it to look. Is there any possibility to change Entry widget disabled bg color to normal?
Or maybe is there another way to make such entry box? :S
The way to do it is with the validatecommand and validate options of the entry widget. This scenario is precisely what those features are for.
You say you "don't know how to make it validate every character the user inputs to the entry box". If you set the validate attribute to "key", that will cause your validate command to be called on every keypress.
Unfortunately, this is a somewhat under-documented feature of Tkinter, though it's documented quite well for Tk. Here's a working example which performs some very rudimentary checks:
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
# define a command to be called by the validation code. %P
# represents the value of the entry widget if the edit is
# allowed. We want that passed in to our validation comman so
# we can validate it. For more information see
# http://tcl.tk/man/tcl8.5/TkCmd/entry.htm#M7
vcmd = (self.register(self._validate), '%P')
e = tk.Entry(self, validate="key", validatecommand=vcmd)
e.pack()
def _validate(self, P):
# accept the empty string, "." or "-." (to make it possible to
# enter something like "-.1"), or any string that can be
# converted to a floating point number.
try:
if P in (".", "-", "-.", ""):
return True
n = float(P)
return True
except:
self.bell()
return False
app=SampleApp()
app.mainloop()
If you search this site for [tkinter] validatecommand you'll find many other examples.
I am working on a PyGTK GUI project, and i would like to know, is there any way to get variable value from gtk.Entry?
text=gtk.Entry(0)
text.set_activates_default(True)
port = text.get_text()
This doesn't work as, the text box is empty by default, and get_text() returns empty string, any ideas?
This doesn't work as, the text box is empty by default, and get_text() returns empty string, any ideas?
Sounds like you're looking for getting the text after some user input. In order to do this, gtk uses signals that allow you to connect a user action to some function that will do something. In your case you want this function to get the text from the input. Because you haven't described the user interaction I'll give the simplest example. If you had a button
in your GUI that, when clicked, would grab whatever is typed in the entry at that moment, you'd do this:
button = gtk.Button( 'Click Me')
button.connect( 'clicked', on_button_click )
Then, you define the on_button_click function:
def on_button_click(self, widget, data=None):
port = text.get_text()
print 'Port: %s' % port
So with the sample code above, you'd have a button that, when clicked, grabs the text from your gtk.Entry.
Check out this link for a simple example on how to use signals in pygtk
Since your text field is by default empty, get_text() would return empty string.
Add a button callback function or some other function. So whenever that function is called, you would get the string from the Entry using
text.gtk_text()
You might want to use self here. since you'll be accessing entry in some other function and not in main thread, use
self.text=gtk.Entry()
self.text.set_activates_default(True)
def foo(self,widget,event): # some callback function
port = self.text.get_text()
print port
The retrieving method is the correct one, but right after the creation, the user can't yet have typed anyting into the field.
You would have to wait for the user to actually type something into the field, and afterwards calling get_text().