How to open Control Panel in python using win32 extension - python

I am interested in being able to open the control panel through python using the win32 extension.
What I really want to be able to do is open the 'Internet Properties' panel (Control Panel > Network and Internet > Internet Options), but I'd figured getting the control panel open would be a good enough start.
For those using Chrome, if you go to Menu > Settings > Show Advanced Settings > Change proxy settings... , the Windows 'Internet Properties' box shows us.

According to this page and this one, you could use something like:
import win32api
import win32con
win32api.WinExec(
'{0}\\control.exe Inetcpl.cpl'.format(win32api.GetSystemDirectory()),
win32con.SW_NORMAL
)
# or
win32api.WinExec('control.exe Inetcpl.cpl', win32con.SW_NORMAL)
Internet Options dialog should pops up now.
Yon don't really need win32 extension for this, you can use something as simple as:
import os
os.system('{0}\\System32\\control.exe Inetcpl.cpl'.format(os.environ['WINDIR']))
# or
os.system('control.exe Inetcpl.cpl')

import os
from tkinter import *
def open():
os.system('cmd /c control') # thi is what will help you
root =Tk()
root.geometry('400x400')
b = Button(root, text='open control panel', command = (open)).place(x=200, y=200) # you can choose your own position
root.mainloop()

Related

Why the icon doesn't display in System Tray although the python code is executing without any error?

I have just started learning python and trying to create a system tray icon. This program is executing without any error but isn't displaying any icon.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
app = QApplication([])
app.setQuitOnLastWindowClosed(False)
# Adding an icon
icon = QIcon("fb.png")
# Adding item on the menu bar
tray = QSystemTrayIcon()
tray.setIcon(icon)
tray.setVisible(True)
# Creating the options
menu = QMenu()
option1 = QAction("Option1")
option2 = QAction("Option2")
menu.addAction(option1)
menu.addAction(option2)
# To quit the app
quit = QAction("Quit")
quit.triggered.connect(app.quit)
menu.addAction(quit)
# Adding options to the System Tray
tray.setContextMenu(menu)
app.exec_()
This code displays following output in VSCode
[Running] python -u "e:\python\systray\systray.py"
When you handle external files as the icon then you must use absolute paths either explicit or build them, in your case I assume that the .png is next to the script so you should use:
import os
CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
# ...
icon = QIcon(os.path.join(CURRENT_DIRECTORY, "fb.png"))
# ...
Maybe try tray.show() instead of tray.setVisible(True).

How to hide console when displaying an image with Tkinter

I have a simple code block that displays an image when the user press a button. When I save the script with .py extension, there is console at the background so I decided to save it as .pyw to hide it. Here is my code;
from tkinter import *
from PIL import Image
def open_image():
im = Image.open("tobi.jpg")
im.show()
root = Tk()
root.geometry("800x600+400+300")
buton = Button(root)
buton.config(text = "Show the image", command = open_image, activebackground = "yellow", bg = "lightgreen")
buton.pack()
mainloop()
I don't see cmd at the background since I save it as .pyw. However, when I click the button, just before opening the image I see console for a short time, then it dissappears. How can I avoid this, I want to hide console completely,
I dont know how to do this through pure tk but if subprocess is an option then you can do the following. Not a very good solution, since you have to use the subprocess module just to open an image... but anyways....
import tkinter as tk
import subprocess as s
root = tk.Tk()
def open_image():
s.call(["tobi.jpg"], shell=True)
button = Button(root)
button.config(text="Show the Image", command=open_image, activebackground="yellow", bg="lightgreen")
button.pack()
root.mainloop()
alternatively you could use os and use os.system("start my_file_name.jpg")
(assuming windows here)
With os.system the console will show but only very briefly.
Really doing the same thing, opening with PIL is just slower than others, so you see the console for a longer period.
U can use the following code:`
import win32console
import win32gui
win=win32console.GetConsoleWindow() # For closing command window
win32gui.ShowWindow(win,0)
This will close the cmd window at start itself, and will not show again. The cmd window may show for a very little time at first, as a blink, then it will not show. u can save in .py extention.
here the full code:`
from Tkinter import *
from PIL import Image
import win32console
import win32gui
win=win32console.GetConsoleWindow() # For closing command window
win32gui.ShowWindow(win,0)
def open_image():
im = Image.open("tobi.jpg")
im.show()
root = Tk()
root.geometry("800x600+400+300")
buton = Button(root)
buton.config(text = "Show the image", command = open_image, activebackground = "yellow", bg = "lightgreen")
buton.pack()
mainloop()

how do I get Tkinter askopenfilename() to open on top of other windows?

I am running a script that prompts the user for a file. There is no gui except for the file browser that opens up. I have 2 options: browse for file, or select entire folder using askdirectory(). The latter opens on top of all other windows, but the first one opens under everything, I have to minimize other windows to find it.
Here is the method I'm using for these operations
from Tkinter import Tk
from tkFileDialog import askdirectory, askopenfilename
root = Tk()
root.withdraw()
self.inpath = askdirectory() # To open entire folder
Path = askopenfilename() # Open single file
root.destroy() # This is the very last line in my main script.
This is everything Tk related in my code. askdirectory opens on top, askopenfilename doesn't.
Is there a way to force it to open on top?
root.wm_attributes('-topmost', 1) did it for me. I found it in another SO thread to be honest :-).
I had the same problem.
For me it works with:
file = filedialog.askopenfilename(parent=root)
So, the file dialog gets in front of toplevel window without uncomment root.attributes("-topmost", True)
I want to share that the following lines worked superbly in my case. But I had to use both window.wm_attributes('-topmost', 1) and window=parent to make this work, see below:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
window.wm_attributes('-topmost', 1)
window.withdraw() # this supress the tk window
filename = filedialog.askopenfilename(parent=window,
initialdir="",
title="Select A File",
filetypes = (("Text files", "*.txt"), ("All files", "*")))
# Here, window.wm_attributes('-topmost', 1) and "parent=window" argument help open the dialog box on top of other windows
I had the same issue of the file dialog window opening below my current window but I couldn't reproduce the issue with your code (in Python 2 or 3).
This is the minimal example where the issue occurs (context is Windows 10, Python 3, script is called from Idle, and note the input function:
File dialog opens below:
from tkinter import filedialog, Tk
root = Tk()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
To open file dialog on top, both root.lift() or root.attributes("-topmost", True) work (but the latter is specific for Windows)
from tkinter import filedialog, Tk
root = Tk()
#root.attributes("-topmost", True) # this also works
root.lift()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
I'm running python 3.x so there is a difference in code, but both opened on top for me. Try giving it focus, it should put in on top.
self.inpath.focus()
I'm not sure if it's gonna work, since I cant reproduce the problem.

Finding GUI elements with pywinauto

I am trying my first things with pywinauto.
Now I want to make use of print_control_identifiers() but I get errors, however I write my code - I cant get any information about GUI objects.
I already tried to generate the code via swapy - had a lot of generated code, but no success.
This is my code so far:
import getpass, fnmatch
from pywinauto import application
currentUser = getpass.getuser()
if fnmatch.fnmatch(currentUser, "axe"):
pwa_app = application.Application()
w_handle = application.findwindows.find_windows(title=u'Login - 0.9.347', class_name='WindowsForms10.Window.8.app.0.141b42a_r11_ad1')[0]
window = pwa_app.window_(handle=w_handle)
window.SetFocus()
ctrl = window['Log In']
ctrl.Click()
else:
print "You need admin rights for that action"
Can you tell me, where I need to use print_control_identifiers()?
Do you have any other GUI automation frameworks that are more up-to-date?
PrintControlIdentifiers() is useful for top level window. If window is top level window specification, then just call
window.PrintControlIdentifiers()
or
pwa_app.Window_(title=u'Login - 0.9.347', top_level_only=True).PrintControlIdentifiers()
A few examples:
Swapy is good to identify the properties. Also, the examples given with pywinauto are quite helpful.
Source: https://pywinauto.googlecode.com/hg/pywinauto/docs/getting_started.html
from pywinauto import application
app = application.Application.Start("Notepad.exe")
app.Notepad.print_control_identifiers()
app.Notepad.MenuSelect("Edit->Replace")
app.Replace.print_control_identifiers()
from pywinauto import application
from pywinauto import application
app = application.Application()
app.Start("Notepad.exe")
Wnd_Main = app.window_(title_re=".*Notepad")
Wnd_Main.MenuSelect("File->Save")
Wnd_Save = app.window_(title_re="Save As")
Wnd_Save.Edit1.SetEditText("Hello World.txt")

A problem with downloading a file with Python

I try to automatically download a file by clicking on a link on the webpage.
After clicking on the link, I get the 'File Download' Window dialog with 'Open', 'Save' and 'Cancel' buttons. I would like to click the Save button.
I use watsup library in the following way:
from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Download")
SaveButton = findControl(optDialog,wantedClass="Button", wantedText="Save")
clickButton(SaveButton)
For some reason it does not work. The interesting thing is that exactly the same
code works perfectly to click on 'Cancel' button, however it refuses to work with
'Save' or 'Open'.
Anybody knows what I should do?
Thank you very much,
Sasha
Sasha,
It is highly likely that the file dialog you refer to (the Security Warning file download dialog) will NOT respond to windows messages in this manner, for security reasons. The dialog is specifically designed to respond only to a user physically clicking on the OK button with his mouse. I think you will find that the Run button will not work this way either.
Try this:
from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Download")
SaveButton = findControl(optDialog, wantedClass="Button", wantedText="Submit")
clickButton(SaveButton)
Sasha,
The code at this link is supposed to work. It uses ctypes instead of watsup.winGuiAuto, and relies on win32 calls. Here is the code:
from ctypes import *
user32 = windll.user32
EnumWindowsProc = WINFUNCTYPE(c_int, c_int, c_int)
def GetHandles(title, parent=None):
'Returns handles to windows with matching titles'
hwnds = []
def EnumCB(hwnd, lparam, match=title.lower(), hwnds=hwnds):
title = c_buffer(' ' * 256)
user32.GetWindowTextA(hwnd, title, 255)
if title.value.lower() == match:
hwnds.append(hwnd)
if parent is not None:
user32.EnumChildWindows(parent, EnumWindowsProc(EnumCB), 0)
else:
user32.EnumWindows(EnumWindowsProc(EnumCB), 0)
return hwnds
Here's an example of calling it to click the Ok button on any window that has
the title "Downloads properties" (most likely there are 0 or 1 such windows):
for handle in GetHandles('Downloads properties'):
for childHandle in GetHandles('ok', handle):
user32.SendMessageA(childHandle, 0x00F5, 0, 0) # 0x00F5 = BM_CLICK
It's possible that the save button is not always enabled. While it may look to your eye that it is, a program might see an initial state that you're missing. Check it's state and wait until it's enabled.
[EDIT] But it's possible that Robert is right and the dialog will just ignore you for security reasons. In this case, I suggest to use BeautifulSoup to parse the HTML, extract the URL and download the file in Python using the urllib2 module.

Categories