python GTK entry: cursor to the left when the entry is empty - gtk

I am using a Gtk.Entry and writing from left to right (xalign==0.0).
When the entry is not empty, the cursor is to the right of the text (as expected):
But when the entry is empty, the cursor is on the right:
That is how I create the entry:
def CreateUserEntry(self):
self.user_entry = Gtk.Entry()
self.user_entry.set_width_chars(10)
user_label = Gtk.Label(label="User:")
self.user_entry.set_text(self.args.user)
self.user_entry.connect('activate', self.ActivateUserTextbox)
user_box = Gtk.HBox()
user_box.pack_start(user_label, expand=False, fill=False, padding=10)
user_box.pack_start(self.user_entry, expand=False, fill=False, padding=0)
return user_box
def ActivateUserTextbox(self, widget):
new_user = widget.get_text().strip()
self.args.user = new_user
How do I fix this?
thanks

Related

How to reset a table

It's possible to reset a table scala swing or remove it from the container after clicking on a button ?
I've tried to create a val with that table but I have always a new table stacked under the old
Here is the code :
// here is the most crucial part when the user click on the button, it will append a new table but if we want to start again, it will append bottom of the old one and I want here a kind of reset or removing of table
contents = new BoxPanel(Orientation.Vertical) {
contents += new Label("Hello, you're welcome")
contents += Button("Query") {
val query: ScrollPane = new ScrollPane(changeCountry())
contents -= query
Try {
contents += query
}.getOrElse(Dialog.showMessage(contents.head, "Incorrect input ! This seems that input isn't in that list, write a different code or country"))
}
// this part will ask to the user to write text to the input to display the table in function of the parameter of my function
def changeCountry(): Table = {
val text = Dialog.showInput(parent = contents.head, message = "Write a code of a country or a country", initial = "test")
text match {
case Some(s) => airportRunwayByCountry(s)
}
}
// this below part creates the table
def airportRunwayByCountry(code : String): Table = {
val headers = Seq("Airport","Runway linked")
val rowData = Functions.findAirportAndRunwayByCountry(code).map(x => x.productIterator.toArray).toArray
val tableAirportRunway = new Table(rowData,headers)
tableAirportRunway}
}
Solved with method "remove" of containers
Here is the code :
Try {
if(contents.length == 3 \\ number of items in my Box) {
\\ at this moment, only add the table because none other table exists
contents += new ScrollPane(changeCountry())
}
else {
contents -= contents.remove(3) \\get the id of the old table and remove it at this position
contents += new ScrollPane(changeCountry()) \\ at this moment, this content will have the id n°2, and the loop can start over without errors
}

Class __init__ seems to be starting other Functions within the class?

I'm trying to code a GUI with two login functions and then a third window with a bunch of widgets. The issue I've run into is since I want to take entry values and retrieve them from another function, I figured I should use a Class. However, when I'm running my code, it seems to pop open all of the other Functions in the starting class.
import sys
from tkinter import *
class Gui():
def __init__(self, root):
self.root=root
self.entry = Entry(root)
stvar=StringVar()
stvar.set("one")
self.canvas=Canvas(root, width=300, height=300, background='white')
self.canvas.grid(row=1,column=0, columnspan = 4)
frame = Frame(self.root)
frame.grid(row=2,column=0, sticky="s")
frame2 = Frame(self.root)
frame2.grid(row=0,column=0, sticky = "n")
self.option=OptionMenu(frame, stvar, "one", "two", "three")
label1=Label(frame, text="Stock Mean:").grid(row=2,column=0, sticky="nw")
label2=Label(frame2, text="Stocks").grid(row=0,column=0,sticky = "w")
self.option=OptionMenu(frame2, stvar, "StockOne", "StockTwo", "StockThree").grid(row=1, column=0, sticky = "w")
label3= Label(frame, text="Std Variance").grid(row=2, column=1)
label4= Label(frame, text="Buy Price").grid(row=2, column=2)
label5=Label(frame, text="Sell Price").grid(row=2,column=3)
label6= Label(frame2, text="Auto/Manual").grid(row=0, column=3,sticky= "e")
labelSpace1 = Label(frame2, text= " ").grid(row=0, column = 1, columnspan = 2)
label7 = Label(frame, text = "Sample Mean").grid(row = 3, column = 0)
label8 = Label(frame, text = "Sample Std Variance").grid(row = 3, column = 1)
label9 = Label(frame, text = "Sample Buy Price").grid(row = 3, column = 2)
label10 = Label(frame, text = "Sample Sell Price").grid(row = 3, column = 3)
class Verification():
def __init__(self):
##First Window
self.master = master
label1 = Label(self.master, text = "Username:")
label1.pack()
user = Entry(self.master)
user.pack()
label2 = Label(self.master, text = "Password:")
label2.pack()
password = Entry(self.master)
password.pack()
button = Button(self.master, text = "Login", command = Verification.verify1(self))
self.master.title("Stock Program")
self.master.geometry("400x500")
button.pack()
##self.master.mainloop()
def verify1(self):
self.root1=Toplevel(self.master)
self.root1.title("Stock Broker Login")
self.root1.geometry("500x500")
##Broker Menu
variable = StringVar(self.root1)
variable.set("TestOne")
OPTIONS = ["One" , "Two", "Three", "Four"]
self.m = OptionMenu(self.root1, variable, OPTIONS)
self.m.pack()
##Login for Broker Account
label3 = Label(self.root1, text = "Username:")
label3.pack()
self.user2 = Entry(self.root1)
self.user2.pack()
label4 = Label(self.root1, text = "Password:")
label4.pack()
self.password2 = Entry(self.root1)
self.password2.pack()
self.user2info = self.user2.get()
self.pass2info = self.password2.get()
button2 = Button(self.root1, text = "Login", command =Verification.verify2(self) )
button2.pack()
## button3 = Button(self.root1, text = "Close", command = Verification.closewindow(self))
## button3.pack()
## def closewindow(self):
## self.master.destroy()
def verify2(self):
##if (self.user2info)=="Name":
self.GraphWindow()
##print (self.pass2info)
def GraphWindow(self):
self.root2 =Tk()
gui =Gui(self.root2)
##self.root2.mainloop()
if __name__ == '__main__':
master=Tk()
start = Verification()
master.mainloop()
The first code I used (Which avoided using this Class) did not run into this issue, so the secondary login window would only pop open if the first Login button was trigger( Which would trigger the command Verify1).
Does anyone know how I can prevent the other functions from triggering? Thanks!
In your __init__ method you are calling the methods that you're attempting to use as callbacks, rather than simply passing the function object. EX:
command = Verification.verify1(self)
Should instead be
command = self.verify1
You make the same mistake in verify1 with your binding to verify2

refresh ListCtrl after drag and drop files

I'm relatively new to wxpython - really appreciate it any help you can offer me. Basically, I'm having trouble closing the loop between
1) filling a list called ListOfFiles in my OnDropFiles method below and
2) refreshing the FileList so that it displays the items in ListOfFiles.
I know that if you call
FileWindow(None, -1, 'List of Files and Actions')
right at the end of OnDropFiles, it inits a new frame and draws from ListOfFiles when populating the FileList listctrl... but I was hoping there would be a way to update in the same window. I've tried noodling around with Layout() and calling various methods on my FileWindowObject... but there's been no success.
Thanks so much for your help. I think the answer you give me might lead to a real breakthrough in my understanding of wxpython.
#!/usr/bin/env python
import wx
import sys
import traceback
import time
APP_EXIT = 1
ListOfFiles = []
class FileDrop(wx.FileDropTarget): #This is the file drop target
def __init__(self, window):
wx.FileDropTarget.__init__(self) #File Drop targets are subsets of windows
self.window = window
def OnDropFiles(self, x, y, filenames): #FileDropTarget now fills in the ListOfFiles
for DragAndDropFile in filenames:
ListOfFiles.append(DragAndDropFile) #We simply append to the bottom of our list of files.
class FileWindow(wx.Frame):
def __init__(self, parent, id, title): #This will initiate with an id and a title
wx.Frame.__init__(self, parent, id, title, size=(300, 300))
hbox = wx.BoxSizer(wx.HORIZONTAL) #These are layout items
panel = wx.Panel(self, -1) #These are layout items
self.FileList = wx.ListCtrl(panel, -1, style=wx.LC_REPORT) #This builds the list control box
DropTarget = FileDrop(self.FileList) #Establish the listctrl as a drop target
self.FileList.SetDropTarget(DropTarget) #Make drop target.
self.FileList.InsertColumn(0,'Filename',width=140) #Here we build the columns
for i in ListOfFiles: #Fill up listctrl starting with list of working files
InsertedItem = self.FileList.InsertStringItem(sys.maxint, i) #Here we insert an item at the bottom of the list
hbox.Add(self.FileList, 1, wx.EXPAND)
panel.SetSizer(hbox)
self.Show(True)
def main():
ex = wx.App(redirect = True, filename = time.strftime("%Y%m%d%H%M%S.txt"))
FileWindowObject = FileWindow(None, -1, 'List of Files and Actions')
ex.MainLoop()
if __name__ == '__main__':
main() #Execute function#!/usr/bin/env python
The problem is that all you're doing is adding items to a list, not to the ListCtrl itself. You need to subclass wx.ListCtrl and add an update method of some sort. Then you would call that update method instead of appending to a list you don't use anywhere. Here's one way to do it:
import wx
import time
########################################################################
class MyListCtrl(wx.ListCtrl):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.ListCtrl.__init__(self, parent, style=wx.LC_REPORT)
self.index = 0
#----------------------------------------------------------------------
def dropUpdate(self, path):
""""""
self.InsertStringItem(self.index, path)
self.index += 1
class FileDrop(wx.FileDropTarget): #This is the file drop target
def __init__(self, window):
wx.FileDropTarget.__init__(self) #File Drop targets are subsets of windows
self.window = window
def OnDropFiles(self, x, y, filenames): #FileDropTarget now fills in the ListOfFiles
for DragAndDropFile in filenames:
self.window.dropUpdate(DragAndDropFile) # update list control
class FileWindow(wx.Frame):
def __init__(self, parent, id, title): #This will initiate with an id and a title
wx.Frame.__init__(self, parent, id, title, size=(300, 300))
hbox = wx.BoxSizer(wx.HORIZONTAL) #These are layout items
panel = wx.Panel(self, -1) #These are layout items
self.FileList = MyListCtrl(panel) #This builds the list control box
DropTarget = FileDrop(self.FileList) #Establish the listctrl as a drop target
self.FileList.SetDropTarget(DropTarget) #Make drop target.
self.FileList.InsertColumn(0,'Filename',width=140) #Here we build the columns
hbox.Add(self.FileList, 1, wx.EXPAND)
panel.SetSizer(hbox)
self.Show(True)
def main():
ex = wx.App(redirect = True, filename = time.strftime("%Y%m%d%H%M%S.txt"))
FileWindowObject = FileWindow(None, -1, 'List of Files and Actions')
ex.MainLoop()
if __name__ == '__main__':
main()

how to get autocomplete text box value using lift web

I am using Lift web framework.
I am implementing an auto-complete text box. When I enter some value in the box a drop-down list opens. If I select a value from that list, only then I am able to access value of text box. If I write a value by myself then I get an empty value.
My code :
var friend_name=""
"#bdayReminder" #> AutoComplete("",
getAllName _,
value => takeAction(value),
List("minChars" -> "3"))
private def takeAction(str: String) {
friend_name = str
}
Please suggest a solution
Disclaimer: I'm the author of following library.
I think lift-combobox could achieve what you want, since it has a feature that let user created the value on-the fly. It use select2 jQuery plugin, so you will have a nice look and feel for the drop-down menu.
For example if you need to get the user-created value, it will simply as the following, note that we usually using Option[T] to denote that the value may not be presented, for example, the user may not selected any item in drop-menu at all:
var friend_name: Option[String] = None
val friendsMenu = new ComboBox(
default = None,
allowCreate = true
) {
// This is where you build your combox suggestion
override def onSearching(term: String): List[ComboItem] = {
val names = List(
ComboItem("f1", "Brian"), ComboItem("f2", "Alice"),
ComboItem("f3", "Luke"), ComboItem("f4", "Smith"),
ComboItem("f5", "Brandon")
)
names.filter(_.text.contains(term))
}
override def onItemSelected(selected: Option[ComboItem]): JsCmd = {
friend_name = selected
// The returned JsCmd will be executed on client side.
Alert("You selected:" + selected)
}
// What you want to do if user added an item that
// does not exist when allowCreate = true.
override def onItemAdded(text: String): JsCmd = {
friend_name = Some(text)
}
}
"#bdayReminder" #> friendsMenu.combobox

Python/Gtk3 : How to add a Gtk.Entry to a Gtk.MessageDialog?

Good morning,
I'm trying to add a Gtk.Entry to a Gtk.MessageDialog. With the following code it seems that I added the Gtk.Entry but it's not visible on the dialog window (Python3/Gtk3):
#!/usr/bin/python3
from gi.repository import Gtk
def get_user_pw(parent, message, default=''):
dialogWindow = Gtk.MessageDialog(parent,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.QUESTION,
Gtk.ButtonsType.OK_CANCEL,
message)
dialogBox = dialogWindow.get_content_area()
userEntry = Gtk.Entry()
userEntry.set_visibility(False)
userEntry.set_invisible_char("*")
userEntry.set_size_request(250,0)
userEntry.set_text("Test")
dialogBox.pack_end(userEntry, False, False, 0)
#dialogWindow.vbox.pack_start(userEntry, False, False, 0)
response = dialogWindow.run()
text = userEntry.get_text()
dialogWindow.destroy()
if response == Gtk.ResponseType.OK:
return text
else:
return None
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="MyWindowTitle")
userPassphrase = get_user_pw(self, "SSH key passphrase")
print("User passphrase: " + userPassphrase)
This code prints :
User passphrase: Test
I'm looking for clues about making the entry visible and editable, any help is welcome.
References:
http://python-gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html
http://developer.gnome.org/gtk3/3.2/GtkDialog.html
Simple, versatile and re-usable entry dialog (sometimes referred to as input dialog) in PyGTK
Ok it works now, I needed to show_all() before run(). It took me some times to figure out this simple thing. Debugged code is :
def get_user_pw(parent, message, title=''):
# Returns user input as a string or None
# If user does not input text it returns None, NOT AN EMPTY STRING.
dialogWindow = Gtk.MessageDialog(parent,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.QUESTION,
Gtk.ButtonsType.OK_CANCEL,
message)
dialogWindow.set_title(title)
dialogBox = dialogWindow.get_content_area()
userEntry = Gtk.Entry()
userEntry.set_visibility(False)
userEntry.set_invisible_char("*")
userEntry.set_size_request(250,0)
dialogBox.pack_end(userEntry, False, False, 0)
dialogWindow.show_all()
response = dialogWindow.run()
text = userEntry.get_text()
dialogWindow.destroy()
if (response == Gtk.ResponseType.OK) and (text != ''):
return text
else:
return None
I use it like this :
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="MyWindowTitle")
userPassword = get_user_pw(self, "Please enter your password", "Password")
This may be going about it the hard way if this is just to run a sudo command - you could simply call
os.system('pkexec (yourcommand)')