How to properly display a picture in PyQt5? [closed] - python-3.x

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I am making a podcast application where I want to display channel icons. That's where I asked myself : How do I properly display a picture in PyQt5 ? I read about this:
label = QLabel()
pixmap = QPixmap('image.png')
label.setPixmap(pixmap)
It's often done that way, but I feel a bit, well, uneasy, about it. It feels hackish to me even though there is an extra method to do it like this. Is there any docs passage where the above way is defined as the official standard one ? If not, is there a better way ? Something like
lay = QVBoxLayout()
image = SomeWidget("image.png")
lay.addWidget(image)

All Qt subclasses of QObject (which includes all subclasses of QWidget, since it inherits from QObject) allow setting their Qt properties in the constructor as keyword arguments.
Since pixmap is a property of QLabel, you can create one directly with an image set with the following line:
image = QLabel(pixmap=QPixmap('image.png'))
If you are so bothered about that, then just create a convenience function or class:
def ImageWidget(path):
return QLabel(pixmap=QPixmap(path))
# or, alternatively
class ImageWidget(QLabel):
def __init__(self, path):
super().__init__(pixmap=QPixmap(path))

Related

record a web page using python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to attempt creating a program in python but I don't know how to start. I want the program to do the following :
goes to a specific website URL
Take a 30 seconds recording or video of the entire webpage displayed.
Saves the recording in a video file.
Is it possible to achieve this, and what libraries would I use in python to create a program that does this?
I had an idea that opencv-python could be one of the libraries I could use, is it possible?
Thanks.
For opening a specific URL, you could use the module "webbrowser":
import webbrowser
webbrowser.open('http://example.com') # Go to example.com
For recording the page you could install the modules "opencv-python", "numpy" and
"pyautogui":
pip3 install opencv-python numpy pyautogui
And then use them all to get the final code, which could look something like this:
import cv2
import numpy as np
import os
import pyautogui
import webbrowser
webbrowser.open('http://example.com') # Go to example.com
output = "video.avi"
img = pyautogui.screenshot()
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
#get info from img
height, width, channels = img.shape
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output, fourcc, 20.0, (width, height))
for i in range(95):
try:
img = pyautogui.screenshot()
image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
out.write(image)
StopIteration(0.5)
except KeyboardInterrupt:
break
print("finished")
out.release()
cv2.destroyAllWindows()
The file should save as "video" and should be runnable. Your screen resolution should be detected automatically during a screenshot. If there are any issues within this code, feel free to tell it to me.

How to automate the command line for the input() in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to python and I am using idle 3.7.4. I want to automate command line to input() in python.
For example:
a = input("Please enter your name : ")
I want to add my name without manually typing it. I read about run() method under subprocess module, but I am not sure how to implement it.
Any helps are highly appreciated. Thanks.
you can use the mock library to do this with the builtins. For example, like this:
import mock
import builtins
def input_test():
ans = input("Please input your name :")
return f"your name is {ans}"
def test_input():
with mock.patch.object(builtins, 'input', lambda _: "okay"):
assert input_test() == 'your name is okay'

how can make the button enable and disable in tkinter? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to see that when the user adds something to the entry field my button gets enabled and then when the user deletes that entry my button gets disabled
A way to disable a button is to use this code:
button = tkinter.Button(root, text='enable/disable'))
def switchButtonState():
if (button['state'] == tk.NORMAL):
button['state'] = tk.DISABLED
else:
button['state'] = tk.NORMAL
To get the input out of a text widget would mean that you would have to run this code:
root.after(1000, check_text_box) # I am pretty sure the 1000 is number of milliseconds
What the after function does is every 1000 milliseconds, it calls the check_text_box function
Here is the complete code to make it work:
def check_to_disable_enable():
text = text_widget_name.get(1.0, tkinter.END)
if text == '': # If the textbox is empty
button['state'] = tk.DISABLED # Disables button
else: # If the textbox is not empty
button['state'] = tk.NORMAL # Enables button
# Call this function when the frame comes up
root.after(100, check_to_disable_enable)
I realize that this may be a bit confusing and if it is please don't refrain from asking a question. If this answers your question, please mark it answered.

How to login a site using Python 3.7? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to write a code in python 3.7 that login a site.
For example, When I get username and password, the code should do the login process to the site.
I'm unsure of what you mean, if you're logging into a site or trying to process a login request, but I'm going to assume the former.
There's one way using Selenium. You can inspect element the site to find the id's for the input for username/password, then use the driver to send the information to those inputs.
Example:
from selenium import webdriver
username = "SITE_ACCOUNT_USERNAME"
password = "SITE_ACCOUNT_PASSWORD"
driver = webdriver.Chrome("path-to-driver")
driver.get("https://www.facebook.com/")
username_box = driver.find_element_by_id("email")
username_box.send_keys(username)
password_box = driver.find_element_by_id("pass")
password_box.send_keys(password)
try:
login_button = driver.find_element_by_id("u_0_8")
login_button.submit()
except Exception as e:
login_button = driver.find_element_by_id("u_0_2")
login_button.submit()
This logs into facebook using the chromedriver.

Fresh tutorial on tkinter and ttk for Python 3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Where can I find the most modern tutorial that teaches tkinter together with ttk?
Tkinter seems the only way to go in Python 3 (don't suggest Python 2), and ttk gave me hope for good-looking GUI.
I have found the TkDocs tutorial to be very useful. It describes building Tk interfaces using Python and Tkinter and ttk and makes notes about differences between Python 2 and 3. It also has examples in Perl, Ruby and Tcl, since the goal is to teach Tk itself, not the bindings for a particular language.
I haven't gone through the whole thing from start to finish, rather have only used a number of topics as examples for things I was stuck on, but it is very instructional and comfortably written. Today reading the intro and first few sections makes me think I will start working through the rest of it.
Finally, it's current and the site has a very nice look. He also has a bunch of other pages which are worth checking out (Widgets, Resources, Blog). This guy's doing a lot to not only teach Tk, but also to improve people's understanding that it's not the ugly beast that it once was.
I recommend the NMT Tkinter 8.5 reference.
Themed widgets
Customizing and creating ttk themes and styles
Finding and using themes
Using and customizing ttk styles
The ttk element layer
The module names used in some examples are those used in Python 2.7.
Here's a reference for the name changes in Python 3: link
One of the conveniences of ttk is that you can choose a preexisting theme,
which is a full set of Styles applied to the ttk widgets.
Here's an example I wrote (for Python 3) that allows you to select any available theme from a Combobox:
import random
import tkinter
from tkinter import ttk
from tkinter import messagebox
class App(object):
def __init__(self):
self.root = tkinter.Tk()
self.style = ttk.Style()
available_themes = self.style.theme_names()
random_theme = random.choice(available_themes)
self.style.theme_use(random_theme)
self.root.title(random_theme)
frm = ttk.Frame(self.root)
frm.pack(expand=True, fill='both')
# create a Combobox with themes to choose from
self.combo = ttk.Combobox(frm, values=available_themes)
self.combo.pack(padx=32, pady=8)
# make the Enter key change the style
self.combo.bind('<Return>', self.change_style)
# make a Button to change the style
button = ttk.Button(frm, text='OK')
button['command'] = self.change_style
button.pack(pady=8)
def change_style(self, event=None):
"""set the Style to the content of the Combobox"""
content = self.combo.get()
try:
self.style.theme_use(content)
except tkinter.TclError as err:
messagebox.showerror('Error', err)
else:
self.root.title(content)
app = App()
app.root.mainloop()
Side note: I've noticed that there is a 'vista' theme available when using Python 3.3 (but not 2.7).
I recommend reading the documentation. It is simple and authoritative, and good for beginners.
It's not really fresh but this is concise, and from what I've seen valid either for Python 2 and 3.

Resources