Label fails to render using python.net - python

I'm trying to rebuild a C# .net form I built in visual studio in Python to better suit my needs. After some googling around, I came across the package python.net/pythonnet and it's exactly what I've been looking for. Unfortunately, for some reason, I'm able to get it to generate a window and change the title of the window, but that's about it. I've tried looking at the package's documentation and .net documentation and I'm struggling to try and figure out why.
This is the snippet of the code I'm trying to use:
import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
from System.Windows.Forms import Form, Label
from System.Drawing import Font, Size, Point
window = Form()
window.Text = "Window Title"
window.Title = Label()
window.Title.AutoSize = True
window.Title.Location = Point(8, 9)
window.Title.Name = "Title"
window.Title.Size = Size(780, 65)
window.Title.Font = Font("Serif", 42.0)
window.Title.Text = "Title Test"
window.ShowDialog()
Currently, all this does is open a blank form window that's titled "Window Title".

Related

Unable to open a local HTML file generated in folium using wxPython

I am currently trying to plot GPS coordinates as markers on a map and displaying the result within wxPython.
I have used folium to plot coordinate markers and generate an HTML file:
import folium
fmap = folium.Map([-43.5321,172.6362], zoom_start=12)
folium.Marker([-43.5321,172.6362], popup='Marker1').add_to(fmap)
fmap.save('maparea.html')
I am able to open this HTML file in Firefox without any issues.
I need to create a programme in wxPython to display this HTML file, and I tried implementing the following code:
import wx
import wx.html2
class MyBrowser(wx.Dialog):
def __init__(self, *args, **kwds):
wx.Dialog.__init__(self, *args, **kwds)
sizer = wx.BoxSizer(wx.VERTICAL)
self.browser = wx.html2.WebView.New(self)
self.browser.LoadURL("maparea.html")
sizer.Add(self.browser, 1, wx.EXPAND, 10)
self.SetSizer(sizer)
self.SetSize((1280, 720))
if __name__ == '__main__':
app = wx.App()
dialog = MyBrowser(None)
dialog.Show()
app.MainLoop()
However, all I get is a blank page. If I change the URL in the code to a website (e.g. http://www.google.com), the code above works without issues.
Why am I unable to view the HTML file in wxPython? Is there another way to load and display an HTML file in wxPython? I would prefer to use the HTML file over displaying a screenshot in wxPython, since I would like to retain the ability pan, zoom and click on markers within the map.
(I'm running Python 3.6.8 and wxPython 4.0.3 gtk3 (phoenix) wxWidgets 3.0.5 on Ubuntu 18.04.)
I believe you need to convert the file path into a URL first (i.e. file://path/to/file.html), you can use wxFileSystem::FileNameToURL() function for that.
See https://docs.wxwidgets.org/3.0/classwx_file_system.html#a616610cafdb14b841940d5e6b08a9615
In addition to the file path needing to be a file:///url there appears to be some issue with an invalid character.
Try it without asking for the folium.Marker and you should see a map of Christchurch.
Edit:
folium is using for the Marker the wrong character for a single quote ' it's using ` instead in it's var declarations.
i.e. instead of
var html_280344edc4004eb6b0012ec2e57f9b85 = $('<div id="html_280344edc4004eb6b0012ec2e57f9b85" style="width: 100.0%; height: 100.0%;">Marker1</div>')[0];
it is providing:
var html_280344edc4004eb6b0012ec2e57f9b85 = $(`<div id="html_280344edc4004eb6b0012ec2e57f9b85" style="width: 100.0%; height: 100.0%;">Marker1</div>`)[0];
You can replace them or use webbrowser rather than wx.html2

Change title of Tkinter application in OS X Menu Bar

When you create an application with a GUI using Tkinter in Python, the name of your application appears as "Python" in the menu bar on OS X. How can you get it to appear as something else?
My answer is based on one buried in the middle of some forums. It was a bit difficult to find that solution, but I liked it because it allows you to distribute your application as a single cross platform script. There's no need to run it through py2app or anything similar, which would then leave you with an OS X specific package.
Anyways, I'm sharing my cleaned up version here to give it a bit more attention then it was getting there. You'll need to install pyobjc via pip to get the Foundation module used in the code.
from sys import platform
# Check if we're on OS X, first.
if platform == 'darwin':
from Foundation import NSBundle
bundle = NSBundle.mainBundle()
if bundle:
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
if info and info['CFBundleName'] == 'Python':
info['CFBundleName'] = <Your application name here>
May not be quite what you need but I am surprised no one has mentioned the simple, platform independent way (works with Python 3.x on Win 7) :
from tkinter import Tk
root = Tk()
root.title( "Your title here" ) # or root.wm_title
and if you want to change the icon:
''' Replace the default "Tk" icon with an Application-specific icon '''
''' (that is located in the same folder as the python source code). '''
import sys
from tkinter import PhotoImage
program_directory = sys.path[ 0 ]
IconFile = os.path.join( program_directory ) + "\ApplicationIcon.gif"
IconImage = PhotoImage( file = IconFile )
root.tk.call( 'wm', 'iconphoto', root._w, IconImage )
root.mainloop()

How to get the text of a widget/window using python-xlib?

I'm trying to find the whole text that is currently being edited in gedit window. Firstly i tried to find out the current gedit tab that is focused, by using Xlib.display. Now i got an Xlib.display.window object . Now i want to find out the text that is in that particular window/widget using this window object
And my code is like this
import gtk, gobject, Xlib.display
currentFocus=''
def current_focused:
global currentFocus
display = Xlib.display.Display()
window = display.get_input_focus().focus
wmname = window.get_wm_name()
wmclass = window.get_wm_class()
if wmclass is None and wmname is None:
window = window.query_tree().parent
wmname = window.get_wm_name()
if currentFocused!=wmname:
if window.get_wm_class()[0]=='gedit':
print "\nNow you are in : < %s >" % (wmname,)
# Here i have to find the text of the gedit's widget
currentFocused=wmname
return True
gobject.timeout_add(1000, current_focused)
gtk.main()
is there any API to get the text of a specific widget using Xlib.display.window
Please help me. I'm completely new in this area
Thank you
WM_CLASS / WM_NAME properties are only used to provide information to a window manager ( hence WM prefix ) and not usually set on child windows. Check GTK source code if edit widget sets similar properties, but in general it is not possible for external process to read edit control text

Qt: Take over system open file dialog

I would like to automate the upload of a file to a website using PyQt4's QWebView, but there's a part I can't figure out yet. To upload the file, the website has a button, which opens a dialog from which you are supposed to select the local file. So, these are my questions :) Is there a way to control that dialog once I click the button? Is there a better way to achieve this?
edit
The website is https://maps.google.com/ and I'm uploading a .kml file through My Places > Create Map > Import.
It is possible what you're looking for is QWebPage::chooseFile() (I suppose it depends also on how the website is handling that). Reimplement that and see if it is sufficient. Do whatever you want and return the chosen file path.
EDIT: Now that you provided the link I tested and seems to work.
Ok, to begin let me start with background information and references.
The module that I will be using is pywin32 download here, specifically the win32gui, API reference here.
Now before you can manipulate the dialog you have to "navigate" to the window handle, the following uses win32.FindWindow API Reference here, which looks like this, where the two inputs are the lpclassName in this case #32770 (stands for a dialog) reference here and the lpWindowName which in this case is File Upload,
HWND WINAPI FindWindow(
_In_opt_ LPCTSTR lpClassName,
_In_opt_ LPCTSTR lpWindowName
);
Code to locate file handle:
import win32gui
control = win32gui.FindWindow("#32770", "File Upload")
And it stores the handle, which in my case was 721470.
The next step is locate the handles of the GUI objects in the dialog, i will show an example of the Cancel button. To find the handle, I wil be using FindWindowEx API reference here,
import win32con
import win32api
ButtonHandle = win32gui.FindWindowEx(control, 0, "Button", "Cancel");
win32api.SendMessage(ButtonHandle, win32con.BM_CLICK, 0, 0)
Reference here for the BM_CLICK and here for the SendMessage.
Final code:
import win32gui
import win32api
import win32con
window = win32gui.GetForegroundWindow()
title = win32gui.GetWindowText(window)
control = win32gui.FindWindow("#32770", "File Upload")
ButtonHandle = win32gui.FindWindowEx(control, 0, "Button", "Cancel")
win32api.SendMessage(ButtonHandle, win32con.BM_CLICK, 0, 0)
Another way is to use the watsup.winGuiAuto module, here, example below:
from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Upload")
CancelButton = findControl(optDialog,wantedClass="Button", wantedText="Cancel")
clickButton(SaveButton)
But i believe the easiest way is to use autoit here, i have used it before in pyqt, to shoot out commands.
Hope this helps!
Additional References (pywin32 versions):
win32gui here
win32api here
Here's a pure PyQt4 demo that more or less reproduces the default implementation:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
class WebPage(QtWebKit.QWebPage):
def chooseFile(self, frame=None, path=''):
return QtGui.QFileDialog.getOpenFileName(self.parent(), '', path)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
view = QtWebKit.QWebView()
view.setPage(WebPage(view))
view.load(QtCore.QUrl('https://maps.google.com/'))
view.show()
sys.exit(app.exec_())

Using Glade 3.12 widgets in python

Just as some history, I have been using python for about 5 years now and have finally decided to make my first gui app in Glade.
I started with something basic, I have a button, a Gtkentry and gtktextview
This is what I am trying to accomplish:
on button press, take from the text from gtk.entry and have it appended to the gtk.textview
now the main problem I have is that I can not find descent documentation for how to use the widgets, and the examples I find on the Internet reference both a builder variation as well as another variation of glade project which I can only assume has been discontinued. I would like to learn how builder fits into the python / glade collaboration.
my code so far:
import gtk
import pygtk
def onDeleteWindow(self, *args):
Gtk.main_quit(*args)
def hello(button):
text_buffer.set_text(txtinput.get_text())
builder = gtk.Builder()
builder.add_from_file("dagui.glade")
handlers = {
"onDeleteWindow": gtk.main_quit,
"buttondown": hello
}
builder.connect_signals(handlers)
textarea = builder.get_object("textview1")
window = builder.get_object("window1")
txtinput = builder.get_object("entry1")
window.show_all()
gtk.main()
window.show_all()
gtk.main()
now this all works and pressing the button will print what ever is in the gtk.entry but I can not find how to append it to the textview. I also am not sure what to search for to find documentation, I tried "gtk builder gtk.textview" and pygtk build gtk.textview append" and all other variations.
Though knowing how to simply add the text to the text view would be great, having a link to somewhere where I can get in plain english how to use these widgets I would be forever great-full.
Frob the gtk.TextView, you need to get the gtk.TextBuffer by using the textview's buffer property.
From the textbuffer, you need to get the iterator that points to the end of the buffer with the get_end_iter method. With that iterator, and your text, you can use the textbuffer's insert method.
Edit: Since I don't have the dagui.glade file, I couldn't test it, but see the following code:
def hello(button):
global textarea, txtinput
buffer = textarea.get_property('buffer')
i = buffer.get_end_iter()
buffer.insert(i, txtinput.get_text())
# clear the input window after appending the text
txtinput.set_text('')
I figured it out, I have found out the the gtk.textview.get_buffer actually sets the buffer ID and then the textview.set_text(buffer) isall I needed.
here is the full working code, the glade is just a button, an entry and a textview:
#!/usr/bin/python
import os
import sys
import gtk
import pygtk
def onDeleteWindow(self, *args):
Gtk.main_quit(*args)
def hello(button):
textbuffer = textarea.get_buffer()
textbuffer.set_text(txtinput.get_text())
builder = gtk.Builder()
builder.add_from_file("dagui.glade")
handlers = {
"onDeleteWindow": gtk.main_quit,
"buttondown": hello
}
builder.connect_signals(handlers)
textarea = builder.get_object("textview1")
window = builder.get_object("window1")
txtinput = builder.get_object("entry1")
window.show_all()
gtk.main()
Use this to add text :
textarea.set_text('whatever you want')
and this for adding pango markup ( http://goo.gl/94Pkk ) :
textarea.set_markup('<span size="large>Example</span>')
Here's the documentation : http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html

Categories

Resources