#user-interfaces

1 messages ยท Page 3 of 1

feral plinth
#

not the theme ill be going with

digital rose
#

pyside6 would be the best and easiest to work with

feral plinth
digital rose
#

what they want?

feral plinth
#

dearpygui

#

and tkinter

proven basinBOT
#

:incoming_envelope: :ok_hand: applied mute to @lyric badge until <t:1666332545:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

sleek hollow
#

When using an inherited QAbstractListModel, is it possible to return only a height for SizeHintRole?

#

Without any size hint, my listview properly adds a scrollbar when needed for width, but I'm not happy with the height of my items. I want to change my item height but let the width still smartly calculate what's needed

mighty frigate
#

@sleek hollownope. The size hint is something Qt itself uses and it needs to return what Qt is expecting

#

@sleek hollowthere's 3 things I'd try to do that:

  • create a subclass of QStyledItemDelegate, and overwrite the sizehint() function, call the parent function there to retrieve the correct width and calculate the height you want. It should look something like this :
def sizeHint(self, opt: QStyleOptionViewItem, index: QModelIndex):
    item_size = QStyledItemDelegate.sizeHint(opt, index)
    # modify item_size here
    return item_size
  • Another that might just work is modifying all default item height using the stylesheet of the view
view = QListView()
view.setStyleSheet("""
QListView::item {
    height: 100px;
}
""")

for reference, the stylesheet documentation : https://doc.qt.io/qt-5/stylesheet-reference.html

  • Lastly, modify your parent model data() function to retrieve the parent sizeHint for your index, and modify the item heigh there
proper jetty
#

Hey, when using tksheet I display my data and want checkboxes above the data.

For i in cols:
    s.create_header_checkbox(c=i)```
Works, but the documentation states this can be set with a single "all" statement. I didn't get it to work, any advice?
mighty frigate
#

@sleek hollowyup, the stylesheet way just works:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import typing
import sys

class Model(QAbstractListModel):
    def __init__(self, datas, parent = None) -> None:
        self.datas = datas
        super().__init__(parent)

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return len(self.datas)

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if index.isValid() and role == Qt.DisplayRole:
            return str(self.datas[index.row()])

app = QApplication(sys.argv)

listview =  QListView()
model = Model(range(0, 10))
listview.setModel(model)
listview.setStyleSheet("QListView::item { height: 50px; }")

mainwindow = QMainWindow()
mainwindow.setCentralWidget(listview)
mainwindow.show()

app.exec_()
#

Also it appears that I was wrong about what I told you yesterday : you do need to store your own checkstate datas, Qt won't do taht for you

#

a working example of checkable string list model :

class Model(QStringListModel):
    def __init__(self, datas, parent = None) -> None:
        self.datas = datas
        self.checkdatas = [False for _ in datas]
        super().__init__(parent)

    def flags(self, index: QModelIndex) -> Qt.ItemFlags:
        default_flags = super().flags(index)
        default_flags &= ~Qt.ItemIsEditable
        return default_flags | Qt.ItemIsUserCheckable

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return len(self.datas)

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if not index.isValid():
            return None            
        if role == Qt.DisplayRole:
            return str(self.datas[index.row()])
        if role == Qt.CheckStateRole:
            return Qt.CheckState.Checked if self.checkdatas[index.row()] else Qt.CheckState.Unchecked
        return super().data(index, role)

    def setData(self, index: QModelIndex, value: typing.Any, role: int = ...) -> bool:
        if not index.isValid():
            return False
        if role == Qt.CheckStateRole:
            self.checkdatas[index.row()] = True if value == Qt.CheckState.Checked else False  
            return True
        return False
swift mountain
#

I don't get it...does PyQt5 have anything like "gui" in its library that pyqt6 does not have?

mighty frigate
#

... You already imported QtGui, what more do you want

swift mountain
#

or is it a whole different library idk i am kinda new to interfaces

mighty frigate
#

@swift mountainwhat are you looking for exactly

#

Qt never had a gui library afaik, it does have a QtGui library tho.

swift mountain
#

wait i figured it out..oh lord i am dumb...thats actually a python file named "gui"

digital rose
#

Does anyone know how using tableview in tkk can make it so when a row is selected, a button font is changed?

uncut oar
#

I'm building a command line tool with argparse and the documentation for the actions keyword arg to add_argument (https://docs.python.org/3/library/argparse.html#action) strikes me as weird. What's the use case for action='store_true' and action='store_false' when default=True and default=False does the same thing?

sudden coral
charred oracle
#

https://paste.pythondiscord.com/asafunotet - why does this example have a text box, why doesn't the text go into the active application, how I make that happen. I want the on-screen keyboard at the bottom and a much larger place to enter text at the top. Not just the text box but a whole area at the top of the screen where you can enter text. This is an example I copied from someone's github. Also, I want to use pysimplegui to change the color from blue to pink, where would I put the hex color codes for each element of the keyboard?
also why does it use something called Elvis in the code?

devout galleon
#

I can't understand this question. how will that answer be like that. Is there any guidance for that: print(13784346375 % 100). print(13784346375 % 2)

lethal widget
sleek hollow
swift halo
#

Anyone knows how to make a reactive variable in textual hold a function value?

#

The default is either a function or the actual default. If it's a function, textual calls it to get the default value. But if the value is supposed to be a function it obviously breaks

spark tinsel
#

[pyqt]Hello, how to change the value of a QSpinbox to infinite (Well not actual infinite just very long).

ancient sundial
#

I have an image viewer using Tkinter and I'm trying to convert the python file into an exe using pyinstaller.However, when doing so I get the error image1.JPG couldn't be found is there anyway to fix this

swift halo
#

Hmmm I guess that could work

spark tinsel
old tinsel
#

Hey guys,
The 3_alpha version of our package tkmodule , a tkinter utility framework is released!!

Documentation would be available soon on our website.
https://novfensec.herokuapp.com/

pip install tkmodule

It's on pypi , the python package index,
https://pypi.org/project/tkmodule/

Github source code:
https://github.com/novfensec/tkmodule

Youtube live preview:
https://youtu.be/jww2DbrabIU

GitHub

A Tkinter Utility framework. Make GUI more faster using tkinter as base library. - GitHub - Novfensec/tkmodule: A Tkinter Utility framework. Make GUI more faster using tkinter as base library.

TkModule - A Tkinter Utility Framework | Novfensec Inc.

TkModule is a Tkinter Utility Framework used for decreasing code size of python programs written using tkinter and creating GUI in a unique way with built-in utilities that made you work very very Easy.

The 3_alpha version of our package is released for now as it is under testing.
You can...

โ–ถ Play video
scarlet ore
#

Hiii
I've to create an automated code.......to calculate the number of commits for each pull request which every user does.
So I've to fetch the data from the bitbucket repository and calculate the number of times the changes have been done to each pull request
Basically calculating the build statistics corresponding to each pull request and the total number of times build has triggered.

tight forum
#

Just sharing something cool I made with wxpython a long time ago.

#

I don't even know what version of Windows that is. This was circa 2003.

somber hemlock
#

Imagine Python thenbrainmon

spark tinsel
#

Anyone familiar with pyqt pages and tabs for a question?

hollow stump
#

Hey there, I've created a version of Conway's game of life (with classes), using matplotlib. So I have a bunch of buttons, interactivity with the plot, etc. And I want to use TKinter to create a user interface and allow anyone to run the game as an exe. But I don't really know how to embed that class inside the tkinter window. Do I just need to call the figure variable of my class and apply the solution suggested here: https://datatofish.com/matplotlib-charts-tkinter-gui/ ? Thanks in advance

keen temple
#

Its Not xp. 2000 maybe?

hollow stump
hollow stump
#

and I want this

hollow stump
#

yahiaBOOHOO please anyone

#

well ping me if you have a solution

#

I can't find anything relevant online

#

I'd be really grateful

#

I think that's against the rule

autumn spear
#

my bad

proven basinBOT
#

9. Do not offer or ask for paid work of any kind.

autumn spear
#

ok

#

looking for someone to write a bit of code for me? need to have experience with threading and UIs

dm for more info

tribal path
#

inserting matplotlib frame into tk? TkAgg

faint smelt
#

Any kivy guys 'round?

spark tinsel
lament rampart
#

Hello, I have a problem with pyqt5 with multithreading when I am creating a new thread to do some background calculations after a button click this newly created thread is not being destroyed after the end of the function and when I am clicking again the button another thread is created on top of the previous one. Short example: Initially -->MainThread, first click of a button--> MainThread, DummyThread-1, second click of a button--> MainThread, DummyThread-1, DummyThread-2 .... . I know I have to use Signals(pyqtsignal), but I dont know exactly how to use them. Can anyone give me some tips on how to signal the stop of the thread after the end of the function. I tried to follow this tutorial(https://realpython.com/python-pyqt-qthread/) but the finished.emit() signal is not being emitted.

In this step-by-step tutorial, youโ€™ll learn how to prevent freezing GUIs by offloading long-running tasks to worker QThreads in PyQt.

mighty frigate
#

wait wait wait

#

@lament rampart let's take the problems one by one

lament rampart
#

ok

mighty frigate
#

what are you using to create and start your thread

#

there's a few different way to do it wih Qt

lament rampart
#

Ok, I have this line of code that triggers a POS_accept_request function. self.Entry_button_PayPod.clicked.connect(self.POS_accept_request)

#

POS_accept_request function is this:

mighty frigate
#

are you subclassing QObject and moving it to a QThread ? Are you subclassign QThread ? Are you using QRunnable and QThreadPool ?

#

QObject and QThread ok

lament rampart
#

yeah right Qobject and qthread

mighty frigate
#

show me Worker pls

lament rampart
#

one moment

#

Worker class is too big its start is like this:

mighty frigate
#

idc about the urn function

lament rampart
#

my bad

mighty frigate
#

I just want the signal definition and the emit

#

np

lament rampart
#

I am initiliazing the finished variable with a pyqtSignal

mighty frigate
#

looks fine

#

what about the emit ?

lament rampart
#

ok, emit is located inside this bug run function in several points. One point is this one: (Give me a moment)

mighty frigate
#

ok I trust you

lament rampart
mighty frigate
#

when you run your code in debug mode, is there anything showing in the console like "cannot connect signal" blablabla ?

lament rampart
#

No, the code runs fine. The problem is that the created threads in the end of the function are not being deleted.

mighty frigate
#

we'll see about that

#

add

def __del__(self):
        print("--- Worker destroyed")

in your worker class

#

and tell me if the message is printing

lament rampart
#

no the message is not printing

mighty frigate
#

are you in a run mode where messages actually get printed usualy ?

lament rampart
#

Yes I am in run mode. These are the messages

mighty frigate
#

are you sure the signal is actually emitted

#

like, can you put breakpoints on every emits of finishe and check if you actually run on it

lament rampart
#

Ok, before doing that, I have a question. I assigned my thread to the self.pay_thread_1 variable. When I am running self.pay_thread_1.isRunning() is printed False, which means that the thread is not running. But When I am threading.enumerate() (that function creates a list with the active threads) the dummy thread is alive how is that possible?

mighty frigate
#

it may be because you didn't start the thread yet, or it is finished already

#

threading.enumerate() doesn't ring a bell, I'll have to check the documentation

lament rampart
#

I have checked the documentation where it says that:

mighty frigate
#

oh this is a python function

lament rampart
#

Yeah.

mighty frigate
#

I wouldn't trust it too much

#

like, Qt likes doing its own thing

#

I wouldn't be suprised if Qt kept that thread alive behind the scene because Qt reasons

lament rampart
#

Ok. I can see your point.

mighty frigate
#

in that regard I have more faith in QThread::isRunning

lament rampart
#

Yeah, but wont I have in the future a problem with the memory if too many threads are created?

mighty frigate
#

I can make you a working example of Worker/QObject with a correct finished emitting

#

maybe you can use that to compare to your own thing and see what's going wrong ?

#

I mean, if the finished signal isn't emitted, it's perfectly normal that the thread isn't destroyed

#

that's where the problem is

lament rampart
#

Ok, I will try now your proposition of using breakpoints at every self.finished.emit() to see if the signal is emitted. I really appreciate your help @mighty frigate. Message me If I can do something for you in the future.

mighty frigate
#

np

#

that's one of the only thing I can do ok-ish

#

oh also, I noticed you maybe forgot to connect to destroyLater of the QThread when the worker is finished

#

you might want to do that

#

or maybe you're doing it somewhere else idk, but still

lament rampart
#

Let me check that, but I just checked the signal is indeed emitted. So maybe this is the problem.

mighty frigate
#

I don't think it is

#

because the worker isn't destroyed

#

it should, as you've connected the finished signal to the worker deleteLater func

lament rampart
mighty frigate
#

but we're going somewhere, the signal is emitted but isn't received somehow

lament rampart
#

Ok, this is the piece of code, the first line what it does when the worker finishes quit the thread

lament rampart
mighty frigate
#

afaik quitting a thread doesn't destroy it

#

anyway that's not the main problem for now

#

what does exit_UI do ?

#

I'll rephrase

#

you have a QApplication somewhere

#

does exit_UI destroys that QApplication ?

lament rampart
#

exit_UI is a function where I am modifying a widget.

mighty frigate
#

ok

lament rampart
#

self.w is the widget

mighty frigate
#

it's fine then

lament rampart
#

This function is running btw

mighty frigate
#

destroying the QApplication might explain why it's not working because QApplication is reponsible of the event loop. If you destroy the event loop, there's no signal/slot anymore. well afaik.

#

so plan B it is

lament rampart
spark tinsel
#

@mighty frigate @lament rampart can you help a noob? How can I nest tabs inside pages in pyqt? After you finish your problem ofc, I can wait. ๐Ÿ™‚

lament rampart
#

I have one question and I wont spend any more time. The event loop if the run function in the Worker class?

mighty frigate
#

don't bother with the event loop. If you have a QApplication and you're not destroying it, you're fine

lament rampart
#

Ok. I appreciate once more the help. Dont hesitate if you need something. Thanks a lot!

spark tinsel
#

@lament rampart File mou mporw na se prosthesw ws filo? Douleyw ki egw pyqt kai twra mpainw sta workers ktlp. Teleiwnw mia efarmogh ths plakas se ligo kai mporei na se xreiastw /me xreiasteis.

#

@mighty frigate do you happen to know a solution to my issue?

lament rampart
#

@spark tinsel ennoeitai an mporw na boithisw

spark tinsel
#

Thanks!

mighty frigate
#

@lament rampart

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import typing

class Worker(QObject):
    finished = pyqtSignal()
    i = 0

    def __init__(self, parent: typing.Optional['QObject'] = None) -> None:
        super().__init__(parent)
        self.result = 0
        Worker.i += 1
        self.i = Worker.i
        print(f"Worker n{self.i} Created")

    def __del__(self) -> None:
        print(f"Worker n{self.i} destroyed")

    def run(self):
        print(f"Worker n{self.i} running")
        self.result = 42
        self.finished.emit()

class Ctrl(QObject):
    def __init__(self, parent: typing.Optional['QObject'] = None) -> None:
        super().__init__(parent)

    def show_result(self):
        print(self.worker.result)

    def clean_threads(self):
        print("QThread destroyed")
        del self.worker
        del self.thread

    def start(self):
        self.thread = QThread()
        self.worker = Worker()
        self.worker.moveToThread(self.thread)

        self.thread.started.connect(self.worker.run)

        self.worker.finished.connect(self.show_result)
        self.worker.finished.connect(self.thread.quit)

        self.thread.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)

        self.thread.destroyed.connect(self.worker.deleteLater)
        self.thread.destroyed.connect(self.clean_threads)

        self.thread.start()


app = QApplication(sys.argv)

ctrl = Ctrl()

mainwindow = QMainWindow()
btn = QPushButton("Run")
btn.clicked.connect(ctrl.start)
mainwindow.setCentralWidget(btn)
mainwindow.show()

app.exec_()
#

there's indeed some weird things in the python Qt API

#

like, the worker deleteLater signal is never actually called for some reason

#

but the underlying C++ wrapped object is correctly deleted tho

#

I'm not sure I understand wth is going on, but this example does work

#

there's also some dummy threads showing in vscode but I think it's more incompatibility between threading and Qt than a real problem

hollow stump
#

I try to call the figure object from my class Conway and then use the TkAgg on that but it doesn't work

lament rampart
#

I ran your code and I figured out something interesting indeed the threading was deleted everytime run button is pressed, but when I put a breakpoint this happened.

#
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import typing
import threading

class Worker(QObject):
    finished = pyqtSignal()
    i = 0

    def __init__(self, parent: typing.Optional['QObject'] = None) -> None:
        super().__init__(parent)
        self.result = 0
        Worker.i += 1
        self.i = Worker.i
        print(f"Worker n{self.i} Created")

    def __del__(self) -> None:
        print(f"Worker n{self.i} destroyed")

    def run(self):
        print(f"Worker n{self.i} running")
        self.result = 42
        self.finished.emit()


class Ctrl(QObject):
    def __init__(self, parent: typing.Optional['QObject'] = None) -> None:
        super().__init__(parent)

    def show_result(self):
        print(self.worker.result)

    def clean_threads(self):
        print("QThread destroyed")
        del self.worker
        del self.thread

    def enumerate(self):
        print(threading.enumerate())

    def start(self):
        self.thread = QThread()
        self.worker = Worker()
        self.worker.moveToThread(self.thread)

        self.thread.started.connect(self.worker.run)

        self.worker.finished.connect(self.show_result)
        self.worker.finished.connect(self.thread.quit)

        self.thread.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)

        self.thread.destroyed.connect(self.worker.deleteLater)
        self.thread.destroyed.connect(self.clean_threads)
        self.thread.destroyed.connect(self.enumerate)

        self.thread.start()


app = QApplication(sys.argv)

ctrl = Ctrl()

mainwindow = QMainWindow()
btn = QPushButton("Run")
btn.clicked.connect(ctrl.start)
mainwindow.setCentralWidget(btn)
mainwindow.show()

app.exec_()
#

I just added to your code self.thread.destroyed.connect(self.enumerate) and I put a breakpoint at enumerate function and then the threading was not being deleted.

#

@mighty frigate

mighty frigate
#

I'm confident that the thread and the worker are deleted, but I really don't understand why the worker destroyed signal isn't triggered and why threading think there's still threads pending

hollow stump
#

I'm asking once again

#

because I can't figure this out

#

setting the buttons and connecting the functions doesn't seem complicated but I don't see how to make it work

hollow stump
#

I just don't understand how to insert my matploltib figure inside a tkinter window. I've searched online, found several answers from different posts, but I don't see how to apply those solution to my problem, especially because I created classes. Can I create the root window outside the class or should I create it in the init of my classes. I kinda see how to add the buttons, and connect them to my different functions, but what about the animation? Creating buttons resulted in an embedded plot in tkinter, an empty matplotlib window being displayed and a non working animation (only the plot interactivity when you click on a cell works).
I've tried adding the root window to the class, using canvas and FigureCanvasTkAgg. This places the figure inside the tkinter window but it isn't animated anymore.

Class Versus():
  def __init__(self,N):
    ...
    self.root = init_figure.root
    self.root.title("Conway's Game of Life - by ChrisZeThird" )
    self.root.geometry("1080x720")
    self.fig = init_figure.fig
    self.ax = init_figure.ax
    self.fig.suptitle(f'Each player has {self.nbr} cells to place', fontsize=20)
        
    self.canvas = FigureCanvasTkAgg(self.fig, self.root)
    ...
    ## I translated matplotlib buttons to tkinter buttons
    ...
    self.canvas.get_tk_widget().pack(fill="both", expand=True)

and later on I have self.canvas.mpl_connect('button_press_event', self.turn_on) # connect cells management to figure. I also removed the event variable in the button commands and remove the button axes and definition to replace them with tkinter button.

I tried doing it externally to the class. So I made another file and called the class there.

versus = cv.Versus(N)
fig = versus.fig
# Creating Canvas
canv = FigureCanvasTkAgg(fig, master = root)
canv.draw()

get_widz = canv.get_tk_widget()
get_widz.pack()

And that generated a separated figure, so not embedded.

unborn gale
#

@somber hemlock

somber hemlock
#

On the desktop at the top right?

unborn gale
#

at the top middle

somber hemlock
#

You can do this with tkinter

#

Afaik you can even make the edges rounded

unborn gale
#

how would I make the shape without making a window?

somber hemlock
#

Idk about rounded, but tk.Tk has an attribute for that non bordered

#

Search on google, there will be stackoverflow results

unborn gale
#

do i just look up "tkinter shape without seperate window" or something? what i am looking up is not showing anything

somber hemlock
#

Search tkinter borderless window

#

Then search tkinter rounder window

#

Or search the second directly

unborn gale
#

@somber hemlock why is it so big

#

smh

somber hemlock
#

Can't really notice it with your black IDE theme going on

unborn gale
somber hemlock
#

Good

unborn gale
#

oh yeah so how would i center it?

somber hemlock
#

Well you can make it as small as you want can't you

unborn gale
#

the rounded thing is made with length and width

somber hemlock
unborn gale
#

why the sides doingf that ๐Ÿ˜ญ

somber hemlock
#

Search how to get screen size in tkinter

#

Probably root_x or smth

frail shoal
#

anyone here terribly versed in TK?

#

if so, direct message me, I have a few questions

crisp rivet
hollow stump
frigid trellis
#

I am trying to make a node based gui app in tkinter , till now I was able to add the drag and drop for a widget
But I want to add another copy of it when a button is pressed how can i do this ?

#

I want to make it like this

#
  1. How do I add the circle(input & output) ?
  2. How to check if a node is connected ?
  3. Make a clone of a node when I click add gate button ?
crisp rivet
#

Assumin you are using canvas?

stray dawn
#

cursor.execute("UPDATE order_status SET order_status = 'done' WHERE order_status = 'pending' AND order_id = ?", (tree.item(curItem)['Id'][0]))
KeyError: 'Id'

Im trying to get first column row value

#

I do think (tree.item(curItem)['Id'][0])) is wrong but I cant find any other solution dead

pliant pike
#

I'm using pyqt6 and wanted to know how to make a QStackedWidget resize to fit the content of the currently displayed widget exactly

pliant pike
#

Nothing I do seems to be working..

thick apex
#

Please, help
PyQt5, how do scrollable list/table kind of [image text]

#

like on youtube

mighty frigate
#

@thick apex QTableWidget is the simplest

#

probably best to use model/view with QTableView tho but it's more advanced

#

@pliant pike did you try QWidget.adjustSize() ?

#

worst case scenario you can use on of the resize function (setMinimumSize, setFixedSize, setMaximumSize) of QStackedWidget with your content sizeHint()

thick apex
#

I'm seriously a newbie and don't know much about sizing in PyQt5

#

Its possible to push on elements in table, not like cells, but like on whole lines

mighty frigate
#

you're the one in control. What's stopping you from creating a function that insert your whole line cell by cell

thick apex
#

not insert

#

i mean selecting, like pushing on element(line) and

mighty frigate
#

also if you're handling a list and not a table, you should consider using QListWidget instead

#

selecting whole line ?

#

I believe there's a selection policy for that but I'll have to double check

#

to use with the setSelectionBehavior ofc

thick apex
#

its on table widget too?

mighty frigate
#

@thick apex

#

even if the official documentation is in C++ I strongly advice you to go and read it, and search things in it. It can answer most of your questions.

thick apex
#

how to block changing elements text (content) in a table in QTableWidget?

plain cliff
#

Is it good?

somber hemlock
#

The sign up button should be at the middle

#

Because that's the main action on that page

#

Could adjust margins more ig it looks super packed

plain cliff
plain cliff
plain cliff
somber hemlock
somber hemlock
spark tinsel
#

Is there a widget in PyQt to just add a wall of text (non - interactive)? QLabel is only 120 char long, I need something bigger if there is one.

spark tinsel
#

Or is there a way to expand QLabel somehow?

thick apex
#

how to make the column width stretch to the borders of the QTableWidget widget?

#

type of maximum width stretching. I don't have any ideas

thick apex
#

How do Signal for Entire Row Selection in QTableWidget in python pyqt5?

#

?

spring saddle
#

Can anyone help me with aligning "Single" with the other options?
its made w tkinter python

#

this is the coding

a =StringVar()
a1 =StringVar()

label = Label(window, text= 'Sex:').grid()

c = Checkbutton(window, text= "Male", variable= a)
c.deselect()
c.grid(row=0, column=2)

c1 = Checkbutton(window, text= "Female", variable= a1)
c1.deselect()
c1.grid(row=0, column=3)

label = Label(window, text= 'Marital Status:').grid()

MaritalStatusList=['Single', 'Married', 'Complicated', 'Divorced']
checkboxes={}
def ShowCheckBoxes(MaritalStatusList):
    Cbcolumn = 0
    Cbrow = 2

    for Checkbox in range(len(MaritalStatusList)):
        name = MaritalStatusList[Checkbox]
        current_var = IntVar()
        current_box = Checkbutton(window, text=name, variable=current_var)
        current_box.var = current_var
        current_box.grid(row=Cbrow, column=Cbcolumn)
        checkboxes[current_box] = name  # so checkbutton object is the key and value is string
        if Cbcolumn == 0:
            Cbcolumn =2
            Cbrow += 1
        else:
            Cbcolumn = 2
            Cbrow+= 1

ShowCheckBoxes(MaritalStatusList)
eager abyss
fringe coral
#

anyone that can help me with a stopwatch function inside qt designer?

mild whale
fringe coral
thick apex
#

How set...HeaderItem(QHeaderView)?

#

its possible?

#

In QTableWidget

#

I can't figure out how to do it right

fringe coral
#

how do I stop this from resetting its size everytime something changes in the designer

#

it's qtextedit

spark tinsel
# fringe coral it only counts to 0.1 then stops, my conclusion is that it only runs once instea...

You haven't created a signal for when the timer starts, here's an example timer I've found online:
https://linuxhint.com/use-pyqt-qtimer/
You need to assign "False" as initial value to the flag and also set "self.timer.setSingleShot" to False. The way it is now it's like it's saying, if True and just loops forever. I think those two are the issues. I'm a beginner so not sure but it may fix this.

fringe coral
#

thread_manager is just self.thread_manager = QThreadPool()

spark tinsel
fringe coral
#

I figured it out

mild whale
mild whale
prime prawn
#

i am currently making a https://dream.ai/ scraper, and i am using tkinter. is there a way i can make the GUI look a bit better?

cerulean hedge
#

IOS minus 17

#

great

bleak latch
#

What UI framework/toolkit/thing would be best suited to making a schematic editor?

queen trout
#

is there a way to increase the width of this white line in pyqt, these are 2 styled QPlainTextEdit widgets side by side

cerulean hedge
#

uhhh macos

#

ig

prime prawn
fringe coral
prime prawn
somber hemlock
prime prawn
#

does someone know how i can gray out a button in tkinter when not all required entry's are filled in?

[EDIT]
Found a solution

chrome galleon
#

Hello, Can I use vpython and tkinter libraries together? Is there anyone who can help?

keen temple
#

do you mean cpython?

thick apex
#

I want Stretch and Interactive selection resize modes in one time :

table = QWidgetTable()
table.setColumnCount(2) 
header = table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.Stretch)
header.setSectionResizeMode(0, QHeaderView.Interactive)
mighty frigate
thick apex
#

If I want to resize it

#

With mouse

#

Mb other Way?

mighty frigate
#

please give me something I can run

#

preferably short

thick apex
#

Ok

#

@mighty frigate

#
import sys
from PyQt5.QtWidgets import (
    QWidget,
    QApplication,
    QGridLayout,
    QTableWidget,
    QHeaderView,
)


class W(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(600, 400)
        layout = QGridLayout()
        self.setLayout(layout)
        table = QTableWidget()
        layout.addWidget(table)
        table.setColumnCount(3)
        table.setRowCount(4)
        header = table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        header.setSectionResizeMode(2, QHeaderView.Stretch)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = W()
    w.show()
    sys.exit(app.exec_())
#

i want column headers first: to stretch
second: to resize with mouse like by default

mighty frigate
#

how about

#
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class W(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(600, 400)
        layout = QGridLayout()
        self.setLayout(layout)
        table = QTableWidget()
        layout.addWidget(table)
        table.setColumnCount(3)
        table.setRowCount(4)
        header = table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Interactive)
        header.setSectionResizeMode(1, QHeaderView.Interactive)
        header.setSectionResizeMode(2, QHeaderView.Interactive)
        header.setStretchLastSection(True)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = W()
    w.show()
    sys.exit(app.exec_())
thick apex
#

This only last section

mighty frigate
#

so you want the same behavior but not for the last section; only for the first one

#

correct ?

thick apex
#

For all

thick apex
#

I want columns to stratch and after enable to mouse resizing

#

@mighty frigate I have only stretch, how do resizng after?

mighty frigate
#

you know I won't work any faster the more you ping me.

#

give me a minute

thick apex
#

I just asked, I think there may not really be an answer, so don't think I'm rushing you, I'm sorry

mighty frigate
#

my food just arrived I have to go

#

this is where I am

#
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class W(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(600, 400)
        layout = QGridLayout()
        self.setLayout(layout)
        self.table = QTableWidget()
        layout.addWidget(self.table)
        self.table.setColumnCount(3)
        self.table.setRowCount(4)
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Interactive)
        header.setSectionResizeMode(1, QHeaderView.Interactive)
        header.setSectionResizeMode(2, QHeaderView.Interactive)

    def showEvent(self, a0: QShowEvent) -> None:
        ret = super().showEvent(a0)

        v_header = self.table.verticalHeader()
        default_col_width = (self.size().width() - v_header.size().width())/3 - 8 # 8: some borders somewhere ? contentMargins ? needs to investigate
        
        h_header = self.table.horizontalHeader()
        h_header.resizeSection(0, int(default_col_width))
        h_header.resizeSection(1, int(default_col_width))
        h_header.resizeSection(2, int(default_col_width))

        return ret

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = W()
    w.show()
    sys.exit(app.exec_())
#

it's working but it's not perfect, it needs more time

thick apex
#

time is money

#

it is possible to make the rightmost edge of the header attached to the right side of the widget?

winged solar
#

First time using PyQt5 (or any Python GUI framework for that matter) and I can't figure out how to make it so my window updates after every frame. I tried it with calling .update() but that doesn't work. I tried it with .hide(); .show() which actually closed and reopened the window but still didn't actually draw anything. I tried .repaint() but that too didn't work.

Because my actual code would be unnecessary complex I came up with this minimal reproducible example.
When I comment out the loop method it actually shows me the paper at 100, 100 but whenever I let loop execute it just "crashes" and even after the code finished it still doesn't show me anything.

import sys
import time

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

PAPER_IMG = "paper.png"
WIDTH, HEIGHT = 500, 500


def loop(win, elem):
    """This example method just drags a paper across the screen"""
    x, y = 0, 0
    frame = 0
    while x < WIDTH - 15 and y < HEIGHT - 15:  # arbitrary end condition
        time.sleep(1)  # arbitrary sleep (simulates a framerate in actual code)
        print(f"Frame {frame:03}")  # just to see that something is actually happening
        elem.setGeometry(x, y, 15, 15)

        win.update()

        x += 10
        y += 10
        frame += 1


def example():
    # Boilerplate PyQt5 code
    app = QApplication(sys.argv)
    win = QMainWindow()
    win.setGeometry((1920 - WIDTH) // 2, (1080 - HEIGHT) // 2, WIDTH, HEIGHT)  # centralized on a 1920x1080 screen

    # Add an image to the canvas
    elem = QLabel(win)
    elem.setPixmap(QPixmap(PAPER_IMG))
    elem.setGeometry(100, 100, 15, 15)

    # initial draw and loop
    win.show()
    # loop(win, elem)

    sys.exit(app.exec_())


if __name__ == '__main__':
    example()
#

Also the paper.png file in case you want to test-run it yourself (It's a custom 15x15 pixel art, hence the size of 15)

#

So yeah, question is: How can I repaint/update after every frame?

mighty frigate
#

@winged solar can you explains to me what it is you're trying to do ?

#

in 99.9% of the scenarios you want to let Qt do his thing and update the widgets itself

winged solar
#

Can't remove embeds on mobile right now

mighty frigate
#

ok so you're actually in the 0.1% that needs to have some kind of control over the update

#

did you figure out how you're going to display the content yet ?

#

are you going to draw it all yourself, or are you going to create widgets

#

oh the answer is in the snippet, you're going to have widgets

winged solar
#

I have a class Element where each Element has a QLabel with a pixmap set to one of the pixel arts.

#

Element provides functionality to update movement, do collision checks, generate start values for all elements, etc

mighty frigate
#

give me a minute

winged solar
#

The snippet is actually really close to my actual code, just a tad simpler

mighty frigate
#

something like this

#
import sys
import time
import typing

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

PAPER_IMG = "paper.png"
WIDTH, HEIGHT = 500, 500

class MainWindow(QMainWindow):
    def __init__(self, parent: typing.Optional[QWidget] = None, flags: typing.Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags()) -> None:
        super().__init__(parent, flags)
        
        self.frame = 0
        self.x = 0 
        self.y = 0

        self.elem = QLabel(self)
        self.elem.setStyleSheet("background: black;")
        self.elem.setGeometry(100, 100, 15, 15)
        self.elem.show()

        self.timer = QTimer()
        self.timer.setInterval(1000/30) # 30 movement updates per second
        self.timer.timeout.connect(self.updateElement)

    def updateElement(self):
        self.x += 10
        self.y += 10
        self.frame += 1
        self.elem.setGeometry(self.x, self.y, 15, 15)

    def showEvent(self, a0: QShowEvent) -> None:
        self.x = 0 
        self.y = 0
        self.frame = 0
        self.timer.start()
        return super().showEvent(a0)

def example():
    # Boilerplate PyQt5 code
    app = QApplication(sys.argv)
    win = MainWindow()
    win.setGeometry((1920 - WIDTH) // 2, (1080 - HEIGHT) // 2, WIDTH, HEIGHT)  # centralized on a 1920x1080 screen

    # initial draw and loop
    win.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    example()
#

@winged solar

winged solar
#

Thank you, I'll look at it after taking a nap. Trying to fall asleep with a prostate infection is quiet tedious though.

mighty frigate
#

ow well, good luck and good nap

winged solar
mighty frigate
#

np

#

@winged solar if you're new to Qt, you def should take a look at the signal/slots feature

winged solar
#

Beg your pardon?

#

Where can I find that?

mighty frigate
#

in the official Qt documentation

winged solar
#

aight, thank you

#

But that's for PyQt6

mighty frigate
#

the official documentation is in C++, but it doesn't change much. The Qt API is the exact same in python and C++

#

oh right

winged solar
#

Do I need the Qt 5.15 LTS?

mighty frigate
winged solar
#

okay, yes. I needed the Qt 5.15 LTS

#

Just one more thing, the documentation seems to use C++.
Is this also relevant for Python?

#

Is PyQt5 just a wrapper for Qt5?

mighty frigate
#

yes

#

well that's not completly correct to says that

#

but for all purpose you can considere it is

#

afaik PyQt is not really Qt but some other company, while PySide is actually done by Qt

winged solar
mighty frigate
#

but afaik both are just wrappers around the Qt C++ libs

#

and the official C++ Qt documentation is way more complete than any Qt Python doc you may find

winged solar
#

got it, thanks

restive umbra
#

hi guys, i want to make a good looking gui app with python.. can anyone suggest the best libs for gui in py please ?
i dont know with what i'm supposed to continue with, either tkinter or pyqt or anything else ๐Ÿ˜ฌ

rare crater
somber hemlock
#

You don't need the ltest

#

Concepts remain the same

somber hemlock
#

Not a lot

#

Qt is fairly stable to break too much API

#

But that's what release notes are for

coarse mirage
#

So for some reason, running the thread run_program results in paraellel programing for the counting. But the actual window color change only happens at the very end instead of each time:

#PyQt
from PyQt6.QtGui import*
from PyQt6 import QtWidgets
from PyQt6.QtWidgets import*

#Others
import threading
import time
import sys



class MainWindow(QWidget):  
    def __init__ (self):
        super().__init__()
        self.title = "Window"
        self.left = 200
        self.top = 300
        self.width = 300
        self.height = 300
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top,self.width, self.height)
        self.label()
        self.start_button()
        self.show()
        
    def label(self):
        self.loading_window_label = QLabel(self)
        self.loading_window_label.setGeometry(40,40,40,40)
        self.loading_window_label.setStyleSheet('background-color: red')
        
    def start_button(self):
        self.s_button = QtWidgets.QPushButton(self)
        self.s_button.setText('Start')
        self.s_button.clicked.connect(self.run_program)
        
    def run_program(self):
        loading_thread = threading.Thread(target=self.loading)
        loading_thread.start()
        time.sleep(2)
        print("Loading...")
        time.sleep(2)
        print("Loading...")

    def loading(self):
        count = 0
        lock = threading.Lock()
        for i in range(5):
            self.loading_window_label.setStyleSheet('background-color: orange')
            time.sleep(1)
            lock.acquire()
            self.loading_window_label.setStyleSheet('background-color: yellow')
            count+=1
            print(f"Blink Number: {count}")
            lock.release()
        self.loading_window_label.setStyleSheet('background-color: green')
            

if __name__ == '__main__':        
    app = QApplication(sys.argv) 
    ex = MainWindow()        
    code = app.exec()
    sys.exit(code)
#

Any help would be great? ๐Ÿ™‚

shell lily
#

how do i give the path for my icon ? It keeps throwing error - _tkinter.TclError: bitmap "C:\Users\vatsal\pypain\tkinter\icon.ico" not defined root.iconbitmap("C:\Users\vatsal\pypain\tkinter\icon.ico")

thick apex
#

I make

cb = QComboBox()
cb.setEditable(True)
#

then if I input <something> and press Enter, <something> add into combobox items, what I want to do in order for <something> to no longer be added to combobox items with Enter Pressing

#

?

#

.setCount

thick apex
#

how Make QRegExpValidator to string contains only '-' or integer num from 1 to 1000

#

?

somber hemlock
#

Then you don't need the newest book either ๐Ÿ˜›
Tons of applications still use 5.15 to save space. Newer qt releases are heavier

bold roost
#

heya, does TUI's count as something i could ask about in this channel?

tawdry mulch
zealous stirrup
#

hey i want to know that can we make the button in tkinter function only once no matter how many times we click it shouldn't execute the respective command

somber hemlock
zealous stirrup
#

thanks mate

north lark
#

Damn guys I really need help. I ve been creating an app in tkinter for some weeks and now it is the 4th time I am using/introducing photos in it so I basically don't understand why I get this error. I will attach the code in a second. So the error says that the image doesn't exist for some reason..

#
    global gallery_window
    gallery_window = Tk()
    gallery_window.title('Sound Gallery')
    gallery_window.geometry('800x700')
    gallery_window.resizable(0,0)
    open_sound_for_gallery = Button(gallery_window, text = "ADD SOUND", command=chooseSoundInGallery)
    open_sound_for_gallery.pack()
    gallery_button.config(state='disabled')
    gallery_window.protocol("WM_DELETE_WINDOW", on_closing_gallery)



def on_closing_gallery():
    if messagebox.askokcancel("Quit", "Do you want to close SoundGallery?" ):
        gallery_window.destroy()
        gallery_button.config(state='active')


sound_file_items = []

mp3_icon = PhotoImage(file='mp3filetypecover.png')

unknown_icon = PhotoImage("unknownfiletypecover.png")

class GallerySoundFile():
    def __init__(self, name, icon) :
        self.name = name
        self.icon = icon

        #self.icon = icon
    def add_file_to_gallery(self):
        item_container_label = Label(gallery_window, text = self.name, image=self.icon, compound='top')
        item_container_label.pack()




def chooseSoundInGallery(chosen_add_sound_file = ""):
    
    chosen_add_sound_filepath = filedialog.askopenfilename()
    final_add_sound_filename = os.path.basename(chosen_add_sound_filepath)
    

    if '.mp3' in final_add_sound_filename:
        chosen_add_sound_file = GallerySoundFile(name = final_add_sound_filename, icon = mp3_icon)
        print('this is an mp3 file')
        print(chosen_add_sound_file.name)
        chosen_add_sound_file.add_file_to_gallery()
    else:
        chosen_add_sound_file = GallerySoundFile(name=final_add_sound_filename, icon = unknown_icon )
        print('unknown type of file')
        print(chosen_add_sound_file.name)
        chosen_add_sound_file.add_file_to_gallery()```
chilly needle
#

Does adding gif animations cause significant overhead? I'm working with PyQt5 right now, and im thinking of adding animations for changing button states, but I wanted to know if there is too much of a performance hit for it to be worth it. Has anyone done anything like this before?

bold roost
#

does anyone know using textual, how to make it autoscroll?

mighty frigate
#

@chilly needle best is to try for yourself

#

ofc there's an overhead, there's always an overhead, but for most app it's insignificant

vast radish
#

Whats the best option to use out of tkinter, pyqt5 or flet. I just need to make a simple light ui that doesnt rely on anythign except python and can run entirely offline

#

ik a bit of tkinter and i love it, just that it's ui is out of date

#

Ping me when you have a response pls

mighty frigate
#

@vast radish I only use Qt so I wouldn't know, but I can tell you Qt is definitively the most complete of the 3

vast radish
#

is it hard to use

mighty frigate
#

arguably yes

vast radish
#

tkinter is very simple to make a basic ui and get it going

vast radish
mighty frigate
#

are you the kind of guy that reads documentation ?

vast radish
#

not really, that stuff confuses me

mighty frigate
#

well you'll probably struggle then

vast radish
#

unless it is written really well so that it is easy to understand

#

i learnt tkinter from a book lol

mighty frigate
#

there's some key concept you need to know and understand when you work with Qt. Iguess it's true for all libraries tho

vast radish
#

whats the qt docs?

mighty frigate
#

best advice I can give you : the official Qt documentation (in C++) is very nice

#

use it

vast radish
#

ahh ok

#

i do a little coding in c

#

mostly c#

#

but python is my main coding language

mighty frigate
#

tbh it doesn't really matter, the API is the exact same in C++ and Python

vast radish
#

ahh ok

mighty frigate
#

the syntaxe is a bit different but it doesn't change anything

vast radish
#

is pyqt web based?

mighty frigate
#

nop

#

one of the key concept we were talking about

vast radish
#

i need to be able to run it as an exe that can be downloaded very quickly

mighty frigate
#

well I guess that's on you

vast radish
#

so a signal is the start and the slot is the destination

mighty frigate
#

yessir

vast radish
mighty frigate
#

exactly

vast radish
#

can i download qt with pip or is it a standalone app

mighty frigate
#

both

#

with python you can use pip

#

in Cpp you actually have to download Qt yourself

vast radish
#

ahhh

#

i love coding on a mechanical keyboard, Clickety clack all the time

vast radish
fervent onyx
#

I want to make a simple gui app for a project i've made so that anyone can use it. The app just needs to ask for the input, activate the virtual env and run the code. How can i do this?

vast radish
#

virtual env's ewww

#

ahah jk

fervent onyx
#

Hmm is something wrong

vast radish
#

ahaha, no. i just don't use virtual env's

#
Activate the virtual environment
Before you can use this virtual environment, you need to explicitly activate it. Activation makes the virtual environment the default Python interpreter for the duration of a shell session.

Youโ€™ll need to use different syntax for activating the virtual environment depending on which operating system and command shell youโ€™re using.

On Unix or MacOS, using the bash shell: source /path/to/venv/bin/activate
On Unix or MacOS, using the csh shell: source /path/to/venv/bin/activate.csh
On Unix or MacOS, using the fish shell: source /path/to/venv/bin/activate.fish
On Windows using the Command Prompt: path\to\venv\Scripts\activate.bat
On Windows using PowerShell: path\to\venv\Scripts\Activate.ps1
Note that the activated environment only works for the context it was activated in. For instance, if you launch two instances of PowerShell, A and B, and you only activate the virtual environment in instance A, that environment will only apply to A. It wouldnโ€™t apply anywhere else.

Many Python IDEs automatically detect and activate a virtual environment if one is found in the current project directory. Microsoft Visual Studio Code, for instance, can do this when the Python extension is enabled. Opening a terminal inside Visual Studio Code will automatically activate the selected virtual environment.

Source: https://www.infoworld.com/article/3239675/virtualenv-and-venv-python-virtual-environments-explained.html

#

hope that helps, i am useless with virtual env's as i never use them

fervent onyx
#

Ok it worked without the virtual env as well๐Ÿ˜‚

vast radish
#

yeah, i see no point to them unless you have conflicting libaries

#

they require you te set them up and install packages each time. Typical Aussie internet, alot of packages can take a hot minute

vast radish
fervent onyx
#

Is this a python library?

vast radish
#

i got bored the other day and made an api that can remotely start a game server. I need to refine it and add a UI to make the API calls

mighty frigate
vast radish
vast radish
fervent onyx
#

Yeah

vast radish
#

No....... its a saying

vast radish
fervent onyx
#

Oh hahahahah

#

What do you use to make an app then

vast radish
#

i used to use tkinter but ima try my hand at pyqt

mighty frigate
#

Qt does a lot more than just UX too

vast radish
#

...... once i have finished this damn assignment

vast radish
mighty frigate
#

SQL, filesystem, web related things, networking, regex and a lot more

vast radish
#

networking, OoOoOoOo

mighty frigate
vast radish
#

my career is IT and im on the Networking side of it

#

any good tutorial?

mighty frigate
#

well in languages like C++ it's a good thing because you don't install a lot of dependancies usually

vast radish
#

are the modules available in python as well? cos having bluetooth seems useless but cool

mighty frigate
#

but that's not the case with python.

#

like, if you need to do some networking task, you can simply use request

#

for example

vast radish
#

i love that

#

may make building my api server start thingy a UI easier

somber hemlock
#

kivy finally added 3.11 support, looks like wheels will come next release

molten path
#

Can someone help with with tkinter?

#

How do i insert all the content from a txt file into a tkinter Listbox?

eternal sleet
#

hello ๐Ÿ˜ƒhas anyone worked with Zapier webhook and connecting to a Flask Development server? Im trying to connect my Zap to a run a function in my Flask app. anyone dealt with receiving webhooks in Flask? or in Fast API?

pine jewel
#

What's the fastest or best gui to learn?

digital rose
#

wouldnt say best

somber hemlock
#

If you can deal with the fact that it has no type hints

hoary swift
#

Is there a gold standard of CLI format converter design that is worth using as reference when building a new one?

hoary swift
#

Also, best depends on your priorities:
Good mobile support means kivy,
Ships with Python means TKinter,
Works with anything that has a framebuffer is probably one of the dearimgui bindings,
Web support means using a web-specific frontend framework, etc

somber hemlock
#

Kivy is not good at mobile, its only supported

#

Best consider it an alpha for android or ios

halcyon bluff
# pine jewel What's the fastest or best gui to learn?

https://youtu.be/ic0PnF04N-Q
there is also this ^

Qt

Everything you can do with C++ in Qt, you can do with Python instead!
Creating UIs should be fast, fun and flexible. Jumpstart your UI development by utilizing ready-made widgets, controls, beautiful charts and data visualization and create stunning 2D/3D graphics for your Python project.

Qt is a powerful cross-platform application and user ...

โ–ถ Play video
lament rampart
#

Good morning, I am using QgridLayout in pyqt5 desktop app. I am wondering if it is possible to move a QLabel inside its cell.
I have this ui:

#

I would like to move the second row near the first row and the QLabel of the second be at center text of the first row.

mighty frigate
#

QLayout::addWidget can take an alignment as params iirc

#

check the QGridLayout documentation

lament rampart
dry ibex
#

Hello ๐Ÿ‘‹

#

Can anyone tell me what basics i need to learn to get started with gui

#

And also can anyone drop some resources videos to know what GUI is and also learning paths and Some books docs

sharp junco
somber hemlock
#

miles ahead

digital rose
#

There are many graphical user interface (GUI) toolkits that you can use with the Python programming language. The big three are Tkinter, wxPython, and PyQt.

shell lily
#

(TKINTER) how does button placement work when button is placed on a frame? In my code buttons gets croped and the frame size doesnt change , no matter what i do.

copper jackal
#

How can I do closeEvent in PyQt5 without using QMessageBox (for the X button at the top of the window)

sharp junco
copper jackal
static cove
copper jackal
static cove
#
class MainWindow(QMainWindow):
    def closeEvent(self, event):
        print("Trying to close this window")

main_window = MainWindow()

This is super slimmed down and non-functional, but that's how you'd do it

copper jackal
proven basinBOT
#

Hey @copper jackal!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

static cove
# copper jackal https://paste.pythondiscord.com/muwububuva

So the issue is how you're constructing your classes. You want to catch the closeEvent from Form, but that's not something you're subclassing. Rather than creating a generic class Ui_Form that then takes a QWidget as an argument, just subclass QMainWindow directly

static cove
# copper jackal how do i change this

So I don't follow your code 100%, especially how you're passing around Form.
This code doesn't 100% function since I commented out some stuff, but hopefully it gets the point across.

You want to change your Ui_Form to be the main class and have it inherit from either QWidget directly or QMainWindow. You then want to change your code to build directly in this class instead of passing around Form

https://paste.pythondiscord.com/warunuqusu

static cove
copper jackal
#

nothing loads and functions do not work

static cove
#

Right, like I said I did comment out a bunch of things and the code I have there is to show you that you can now catch the closeEvent event. I didn't change it over 100%, that's still up to you

copper jackal
static cove
copper jackal
#

not work ๐Ÿ˜ฆ

boreal halo
#

Is Eel good for GUI development?

hidden mirage
#

I am very slowly building the internals for a system that would help a DM to run combat in a game of Dungeons and Dragons. It isnโ€™t intended to be a virtual tabletop, it wonโ€™t handle maps or movement or anything like that. Itโ€™s just a tool to track initiative, hit points, actions, and so on.

Ideally it will eventually have an interactive interface for the DM, and a โ€œread-onlyโ€ interface for players (probably over the web?)

When Iโ€™m satisfied with the core logic, I will start adding API hooks, probably with FastAPI because I know it a bit.

What I donโ€™t know yet is, what should the UI technology be for the DM? Ideally a user would have to do some setup in advance, but when playing they would just need to press a few keys. Iโ€™d love a hot key system, where the DM could do anything if they need to, but all the most common options are easy to see and easy to pick - ideally just a single keypress.

Can I use a modern TUI for that, at least for a prototype? Can you recommend one?

And for a final version, are there web tools that will allow me to focus on accepting keyboard input? I guess it would be some JS, right?

hoary swift
sullen sundial
#

Holy crap textualize actually has documentation now

#

I've been using it just via source code reading (total pain in the ass)

coarse mirage
#

Is anyone familiar with QThread?
I'm having issues creating a loading screen as shown in #๐Ÿคกhelp-banana
Any help would be great.

somber hemlock
#

Is it new?

sturdy cypress
#

guys how to make tabs in tk?

fiery blade
#

any kivy user here?

leaden zephyr
#

@fiery blade Yea I use it

sturdy cypress
#

there is a way to show pages in a tk window? like a website?

#

can someone pls help me

#

hello?

covert rock
#

could anyone with access to the newest martin fitzpatrick Qt6 book share the pdf with a porr dude from 3rd world?

fiery blade
digital rose
#

does anyone know how to make ascii like this

quick moon
digital rose
sage lava
#

that looks like the ASCII art was probably created by hand

digital rose
#

this box and ascii looks decent

zinc lagoon
#

Yeah

digital rose
#

thats too much work then

zinc lagoon
#

There's a few tools that can do that, I just can't remember any in particular

zinc lagoon
#

See here

quick moon
zinc lagoon
#

Then you just draw a box and the rainbow color, something like rich is pretty good at that. Colorama if you just need simple stuff

digital rose
#

oh thanks!

digital rose
#

just need to get the text

#

in the ascii

shell lily
#

(TKINTER) i have a code , in which i have a while loop which keeps running after the window is closed

#

here is a sample code ```
import Tkinter
from threading import *
root = tkinter.Tk()
def thread():
thread = Thread(loop)
thread.start()
def loop():
while True:
pass
b = tkinter.Button(root,text = 'start', command = thread)
mainloop()

obtuse thistle
coarse prism
#

hey

#

any one could help me with this error?

shell lily
misty canopy
#

I'm using pyside6. How can I do some job in a worker thread, then when it's done, modify something in the GUI in the main thread? I can't have the job itself do that; getting an error due to trying to add children to an element from another thread.

#

Do I need to use, like... some fancy Qt callback mechanism?

eager beacon
#

emit the result from the thread to a callback in the main

misty canopy
#

I'm currently doing this in the GUI thread:

text = self.links_inp.toPlainText()
parts = text.split()
failed = mildly_long_job(parts)
self.links_inp.setPlainText("\n".join(failed))

which works fine, but with a slight delay due to mildly_long_job.

misty canopy
eager beacon
#

its fairly straight forward to do most of the time

threadSig.whatever.connect(self.mainthreacallback)
threadSig.emit(something)
#

Are you using a runnable or Qthread ?

misty canopy
#

I was trying to just submit a callable to a python threadpool

eager beacon
#

there is QThreadpool that works with with signal/slot and there are a bunch of good examples online

#

Thats a nice write up on different methods available for threading and it has boilerplate examples to play with

#

QThreadPool is probably the most complex of the available options but its still easy enough to understand if you're familiar with how threadpools work in general

misty canopy
#

@eager beacon I ended up doing this, which works. How does this look?

class WorkerThread(QThread):
    result_ready = Signal(list)
    def run(self):
        failed = mildly_long_job(parts)
        self.result_ready.emit(failed)

def update_links(failed):
    self.links_inp.setPlainText("\n".join(failed))

text = self.links_inp.toPlainText()
parts = text.split()
thread = WorkerThread(self.app, self)
thread.result_ready.connect(update_links)
thread.finished.connect(thread.deleteLater)
thread.start()
eager beacon
#

That works as is?

misty canopy
#

It does.

eager beacon
#

Oh, yeah.. I guess it might. Are you using a worker object?

#

QObject subclass

misty canopy
#

I don't have any direct subclasses of QObject, no

eager beacon
#

That's usually the best way to go from what I understand though if you search enough you can find an old thread on the old Qt site saying that using QThread alone doesn't have to be a bad thing

misty canopy
#

I assume that's what's used in this horrible, probably autogenerated-from-C++-docs snippet

eager beacon
#

usually you set up a worker that has a callback that does the actual work. generally It's called using mythread.started.connect. When the worker callback is complete it emits the result to wherever you need it to go

#

yeah, i'd be surprised if that worked. you almost always have to use self.worker for self.worker.moveToThread things to work properly

misty canopy
#

It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run() . This means that all of QThread โ€˜s queued slots and invoked methods will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread .
I'm guessing it's because of this gotcha, but in my case that's actually exactly what I want, so the thread-subclass approach works.

eager beacon
#

nice when stuff just works out like that

coarse prism
#

Got it!

digital rose
#
class App(QWidget):
    def __init__(self):
        super(App,self).__init__()
        #setupcode stuff
    def openWindow(self):
        self.apps = QApplication(sys.argv)
        self.w = MainWindow()
        self.w.show()
        #sys.exit(self.apps.exec_())

    def initUI(self):
        self.setWindowTitle("words")
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create textbox
        self.textbox = QLineEdit(self)
        self.textbox.setPlaceholderText("inpit")

        self.textbox.move(20, 20)
        self.textbox.resize(280, 40)

        # Create a button in the window
        self.button = QPushButton('rer', self)
        self.button.move(20, 80)

        # connect button to function on_click
        self.button.clicked.connect(self.on_click)
        self.show()

    @pyqtSlot()
    def on_click(self):
        textboxValue = self.textbox.text()
        self.openWindow()
        self.textbox.setText("")
class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("words")
        self.im = QPixmap("jp.png")
        self.label = QLabel()
        self.label.setPixmap(self.im)
        self.grid = QGridLayout(self)
        self.grid.addWidget(self.label, 1, 1)
        self.label = QLabel()
        self.label.setPixmap(self.im)
        self.grid.addWidget(self.label, 2, 1)
        self.setLayout(self.grid)
        self.show()```yo so i have this pyQT and im trying to open a second window on_click() and it works first click
#

but it errors out on the second

rose silo
#

Question, to call an interface in other file does it need to have classes and that kind of stuff?
this is the case:
I have two files, login and map, login is code with a class that basically gives you correct or incorrect depending the input(user and password), and map it is just the root window with a frame that contains a map with some functions(markers, paths in the streets, etc), and the thing is that I wanna write a condition in login that if the user log in then the map will open, so the question is, can I call something inmap that gives me the entire interface working?

#

let me know if code is necessary, I didn't send it because the interface's code is a bit disorganized, but tell me if it is necessary

wise blaze
static echo
#

Hello

shell lily
#

is there a way , i can set up a shortcut like alt + f5 , for opening a tkinter app?

somber hemlock
digital rose
#

What do you think will be the next metaphor for UIs?

#

I've read that Gen Z see computers as "magic bags", and don't understand, nor follow, the idea of directory structures and "filing cabinets", just use the search bars to get what they need

#

I thought that was very interesting, and started noticing the analogical metaphors implied in all sort of software, and i think its a really interesting idea, one of a non-symbolic? iconic? (i never remember the terms of semiology) UI. To put an example, say art/image manipulation software, do we really need the concept of brushes and canvases when the people using it never used brushes or canvases? Do they think about image manipulation in that way?

sleek hollow
#

people still use the floppy disk as the save icon

#

take away what you will from that, haha

old fjord
#

Is there a module for an ascii text art game user interface?

raw sedge
#

hey guys
are you interesting about converting small images to python code ?? ๐Ÿ˜Ž

proven basinBOT
lament rampart
#

Hello, I have one question. I am using pyqt5 module to build a windows app. I have this qtablewidget and I want to hide grids only from the first column. As I was looking the documentation, I found a method called setShowgrid, but this function deletes all grids from all columns. This is the qtablewidget:

fossil schooner
#

I'm looking for a package for writing terminal applications in a style similar to bpytop. Anyone know of one? Already thought of, you know, looking at bpytop... But it's a single script that's 5,000+ lines long

tribal path
#

rich? or textual. looks like bpytop is using ansi codes directly

hushed prairie
#

Hello , can I get help with GTK here?

crisp rivet
#

Should touchscreen buttons that are meant to be held down to perform a continuous action continue doing the action if the user keeps pressing but moves finger off button?

#

I'm having a problem. onMouseDown works fine on desktop, but when I test touch (in google dev menu), the name of the element is undefined

#
function PutButtonPress(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) {
  const target = event.target as HTMLButtonElement;
  const name = target.name;
  fetch(`/api/set/Dutch_Arm/digital_outputs/${name}?value=${true}`, { method: 'PUT' });
}
crisp rivet
#

Ok, now my problem is that the event target I'm getting is for the icon inside my button.

crisp rivet
#

fixed

old fjord
#

Is there a module for a terminal like system but without all the settings, selection, resizing, etc.?

proper jetty
#

Hey, I'm getting a visual bug with tkinter and tksheet.
I display a table and autosize it depending on the longest text in cells. This can cause a table to be 500px, in the next document maybe only 400px.

When displaying the new, narrower table it's placed visually above the old table and the remaining old 100px are still visible next to it. I can even scroll!

Is there any function to fully flush the page/frame? I tried

sheet.destroy

before but that didn't change it

proper jetty
#

oh well figured it out..
button now destroys the whole frame, via a function, then makes new frame, then new sheet. Couldn't call the .destroy in the same function, as then python throws an error that the variable fameFilter is referenced before initialization

def button_search():
    if randomCondition:
        frameFilter.destroy
        refresh_frameFilter()
        createSheet(data)

def refresh_frameFilter():
    global frameFilter
    frameFilter = customtkinter.CTkFrame(           
                    master=app,
                    corner_radius=15,
                    )
    frameFilter.grid(       
                    row=1,      
                    column=0,
                    pady=(0,0),
                    padx=(20,20),
                    sticky='NWSE',
                    )
foggy schooner
#

Hi! How would you make such an animation in python? The animation is about showing the concept of time division multiplexing. Each user has data to send through the shared medium. Data from all users is combined into frames. Length of the frame is equal to number of users. When user has no data to send the slot remains empty
Link: https://www.youtube.com/watch?v=aeJ55IySP_I.
Here is another example: http://dccanimations.appspot.com/animations/tdm/animation.html
I think it's about moving squares from left to right
Tkinter will do? Or Pyqt5 is the better option? I am not really familiar with GUI development so I am asking more experienced guys what will be the best/fastest option?

TDMA
Every node transmit it's data in it's allocated slot in frame. Frame is divided into multiple slot and each slot assigned to each node.

โ–ถ Play video
old fjord
#

Is there a module for a terminal like system but without all the settings, selection, resizing, etc.?

ebon bison
#

Working with Selenium & tkinter, whats the best approach of having both running and communicating without freeze?
Currently I have selenium on a different thread, there is no freezing up but I cant get it to communicate to tkinter (i want to update tkinter label as selenium is working, such as mentioning what page weโ€™re on)

thick roost
somber hemlock
swift mountain
proper jetty
#

I just realized I get resolution problems on Laptop vs Desktop. Laptop has resolution scale set to 125% (16" display) and desktop is 100%.
My app looks well on the 125% setup and wrong on 100%. is there any way to easily fix it? i pass width and height in px to tkinter widgets and the window size.

#

first image is on laptop, second on desktop

sleek hollow
#

I know how to get DPI with PyQt but not really sure with tkinter

mighty frigate
#

@sleek hollow that's the same kind of solution we have implemented in our product here too

#

but it's more like a quick fix than an actual solution honnestly. Best would be to do like most website do : have a set of target resolution, and reorganize the UI for each of those

sleek hollow
proper jetty
mighty frigate
#

sadly it doesn't work in all cases

proper jetty
#

One downside is this makes a small window flash up shortly.

mighty frigate
#

for example, you can customize the text size on windows

#

the resolution alone isn't a good enough indicator

proper jetty
mighty frigate
#

to solve the windows flashing, you could use another lib to get the screen size

proper jetty
sturdy cypress
#

hello

#

can someone help me

#

hello can someone help me im making a pyqt5 tabless browser and i need to know how to add key inputs to it (space to open the same program again and R to reload) pls help here is my code:

ebon bison
somber hemlock
spring sinew
#

Is it normal that when I use PyQt5 in VS Code, I get no autocompletion for methods like setCentralWidget or even any documentation describing what kind of parameters classes, functions and methods accept?

ripe shuttle
somber hemlock
#

!pip PyQt5-stubs

proven basinBOT
somber hemlock
#

Wish kivy had type hints...

shell lily
somber hemlock
shell lily
somber hemlock
#

Tkinter is quite bad perf-wise. You might have some better luck with canvas ig

vivid dagger
#

Hi, if I make an application in python using tkinter for my gui, will users have to manually install packages like tkinter and customtkinter? Or will the application just work for them out of the box.

somber hemlock
#

sudo apt install python3-tk

shell lily
vivid dagger
shell lily
#

Using pip

vivid dagger
#

It will just be a setup.exe file that includes everything needed?

shell lily
#

Yes ,user can just use it as normal desktop app

vivid dagger
#

Ok thx man

shell lily
#

Gather all your necessary files in one folder
Than go to that directory in command prompt
Type : pyinstaller {main file of your app.py} --onefile --noconsole

vivid dagger
swift mountain
#

How to modify the UI after I've converted the .ui file into.py file...is there any way to modify it with Qt designer once it's converted to .py file?

somber hemlock
#

You can manually modify the code in .py file as well

swift mountain
somber hemlock
#

You shouldn't even be touching the .py file created by qt, you are supposed to write your code in a different module

swift mountain
#

Is there any way I can replicate that network activity graph in python? apart from matplotlib

spring sinew
#

Would you recommend using Qt Designer and loading .ui files when working with PyQt? That seems quite helpful initially but it feels like it would cause more issues down the road compared to just purely doing it via Python.

mighty frigate
#

@spring sinew Qt devs recommand using Qt Designer

#

I personnaly hate it and I don't use it

spring sinew
#

Is there any reasoning behind their recommendation and your hate?

mighty frigate
#

this is a litteral quote from a conversation I had a few months back with a dev from Qt

#
creating an UI manually is tedious and not error-proof 
unless you 100% understand the spacers, layouts, size policies let Designer do it for you. if you 100% understand 
2 situations:
* if you don't fully understand spacers, layout, size policies, ... โ†’ use QtDesigner.
* else โ†’ use QtDesigner
#

and I personnaly don't like it for 2 main reasons :

  • I feel like I'm not in control of the generated code
  • More often than not you need to customize the widgets you're using and you need to code it anyway
rocky dragon
#

I found it useful for prototyping how things should look, but other than that after maybe a week of using Qt it's faster to code manually anyway

swift mountain
#

Like it's kinda messy when you need to modify your UI after converting to .py... with tkinter you know what you're doing because you're writing the code yourself instead of generating

spring sinew
#

Isn't that problem resolved by just not using Qt Designer and entirely writing it yourself?

swift mountain
#

Yeah then there's not much difference...but I guess people use pyqt for the designer

#

Also what I personally experienced is that PyQt has steep learning curve

#

I found tkinter less of a headache

mighty frigate
#

PyQt is, afaik, way more capable and has way more features than tkinter

#

it depends on your need I guess

ebon bison
#

Trying to update a label inside my app class from another class that inherites the app class, even declared it app=App() but it cant find the attribute label, what might I be doing wrong?

mighty frigate
#

you need to specify what lib you're using.

ebon bison
#

Sorry, tkinter + custom tkinter

somber hemlock
#

Those that already use qt for desktop apps would find pyqt easy

mighty frigate
#

^ can confirm that

#

it's the exact same

short badger
#

does anyone know where to find simple practical example of something made with tkinter (only the original modules no extensions or anything)

sullen pendant
#

Hi there, for some reason I'm struggling putting together a UI using Tkinter, I can't get the actual user input from text fields. Is there a more user friendly library than Tkinter?

sleek hollow
sullen pendant
sleek hollow
#

and tkinter is typically regarded as one of the more user friendly ones

#

just as I thought ๐Ÿ˜‰

#

never .place() on the same line you assign your widget

sullen pendant
sleek hollow
#
widget = Button().place()
#
widget = Button()
widget.place()
sullen pendant
#

Haha is that really the issue?

sleek hollow
#

yes, you've assigned widget to the return value of place() instead of Button() (as in my example)

#

and place() has no return

#

very common mistake

sullen pendant
#

Lol thats hilarious, thank you. I'll give that a shot

#

Thanks!

sleek hollow
#

it's ok to do this for widgets that you don't need to reference to later (like labels/buttons)

#

but anything you need to interact with again, you must separate it out like that

sullen pendant
#

Gotcha, I'll keep note of that. Thank you

#

@sleek hollow darn, no luck. Still getting "PY_VARX". Any other thoughts?

#

The text inputs lines are now of the form...

self.widget_input = tk.Entry(self, textvariable=self.var_name)
self.widget_input.place()

#

I've looked into using trace() as well, would that help here?

sleek hollow
#

@sullen pendant Here's a super basic example of getting the text from an entry

#
import tkinter as tk 

def print_text():
    print(e.get())

root = tk.Tk()
root.geometry('200x50')
e = tk.Entry()
e.pack()
tk.Button(text='Press Me', command=print_text).pack()
root.mainloop()



#

Type something in the entry. When you press the button, it will print to console what text the entry has

sullen pendant
#

I haven't seen this pack(), maybe that's my issue?

sleek hollow
#

place and grid are the other ways

#

.rp tkinter

buoyant cometBOT
#

Here are the top 5 results:

Python GUI Programming With Tkinter
Build a Tic-Tac-Toe Game With Python and Tkinter
Python sleep(): How to Add Time Delays to Your Code
Arduino With Python: How to Get Started
PySimpleGUI: The Simple Way to Create a GUI With Python
sleek hollow
#

I recommend that first realpython tkinter article. That's where I first started and it helped me out a lot

sullen pendant
#

Much appreciated!

sleek hollow
#

What's the best way to approach filtering a model/view in PyQt? I have a class inheriting from QAbstractListModel, and it contains a list full of items from another custom class. Those objects have a bool attribute and I want a toggle to only display the ones with a True value. I tried using an if to only return the True objects but the False ones still show up (just without a display name or icon)

sleek hollow
#

Ended up using a buffer list to hold all the master objects and another to hold the filtered objects, and then I use that as my model. Not sure if this is the most efficient approach but it seems to get the job done for now

young imp
#

Wait what

#

You can make UI with Python?!!?

vital dome
mighty frigate
earnest quest
#

So I just started to create a UI and I'm planning to divide each section into classes to keep my code more organized. Here's what I have so far:

import tkinter as tk
from tkinter import ttk

class MainFrame(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.grid(row=0, column=0)

I'm planning to set the positions of widgets using grid inside the init method. If I want to position the main frame itself, I'd use self.grid(ARGUMENTS) but if I wanna position a widget inside that frame, I'd use self.widget.grid(ARGUMENTS).


The main problem I have here is the similarity of those two lines mentioned above. I'm afraid that it may confuse some people, since the main frame is positioned relative to its parent and the widget is positioned relative to the main frame. The lines also look very similar so I'm afraid that people may mistaken self.grid(ARGUMENTS) as positioning a widget instead of the main frame. As a result, I'm afraid my code will end up being a clutter of elements, some placed relative to the main frame and some placed relative to the parent of the main frame, with no way to find out which is placed relative to which. What should I do to fix this? Should I add comments to clear the confusion or is there a better way?

somber hemlock
sleek hollow
mighty frigate
#

@sleek hollow so if you look at the presentation of the class, you'll see something like this :

model = MyModel(some_datas)
proxymodel = MyProxyModel()
proxymodel.setSourceModel(model)
myview.setModel(proxymodel)

As you can see, proxy models are models that wrap other models

#

@sleek hollow they provide some usefull builtin features that you can customise, like sorting and filtering

#

for filtering, proxymodels have a method that you need to overwride :

class MyProxyModel(QSortProxyModel):
    def filterAcceptsRow(self, sourceRow: int, sourceParent: QModelIndex) -> bool:
        return True if something else False
#

(this is an example for the rows, there's a similar functions for columns)

Applied to your case :

class MyProxyModel(QSortProxyModel):
    def filterAcceptsRow(self, sourceRow: int, sourceParent: QModelIndex) -> bool:        
        source_index = sourceModel()->index(source_row, self.filterKeyColumn(), source_parent);
        return source_index.data(MyCustomRoleForMyInternalBoolData).toBool()

This is untested and ported from C++, this might not be exactly correct but you get the idea

spring sinew
#

I am reading a book about PyQt and came across this block of code

import os
  if filename:
    if os.path.exists(filename):
      write_confirmed = QMessageBox.question(
        self,
        "Overwrite file?",
         f"The file {filename} exists. Are you sure you want to overwrite it?",
      )
    else:
      write_confirmed = True
    if write_confirmed:
      with open(filename, "w") as f:
        file_content = "YOUR FILE CONTENT"
        f.write(file_content)

which is responsible for handling already existing files when you want to save a file via QFileDialog.getSaveFileName(). Do I even need this? Apparently the native Windows dialog which pops up already checks if a file exists without me having to code the check myself.

arctic kayak
#

ThAt'S iLlEgaL

mighty frigate
#

@spring sinew afaik Qt already check for this. You can verify for yourself by browing the Qt code directly

sleek hollow
spring sinew
# mighty frigate <@141659455266881536> afaik Qt already check for this. You can verify for yourse...

On Windows, and macOS, this static function will use the native file dialog and not a QFileDialog.
https://doc.qt.io/qt-6/qfiledialog.html#getSaveFileName

From what I understand, Qt just lets the OS native file dialog do its job when it is run on Windows or macOS. I don't use macOS but I would guess that its native file dialog also checks for existing files. Though I couldn't find anything about Qt's own file dialog checking for existing files if it e.g. runs on Linux.

mighty frigate
#

@sleek hollow I don't think so. Other than it might be maybe less efficient.

#

@spring sinewthis is a very old ticket you got there

#

Qt4.6, in 2010

#

as to your problem, I have no idea. I've never tried for myself.

sleek hollow
exotic parrot
#

in DearPyGui how do i make the viewport cords max to the window

#

basically the window border is the actual window the of the application

exotic parrot
#

nvm i got it

#

dpg.set_viewport_max_height(HEIGHT)
dpg.set_viewport_max_width(WIDTH)

swift halo
#

Can someone suggest resources for learning UI design? I'm not interested in learning a particular tool, but more broadly, how to design good interfaces.

vast tinsel
#

not sure if this counts as user interface but i made a screen module for the terminal

#
scnmem = []
import os
def cls():
    print("\033[H\033[J") 
    if os.name == "nt":
        os.system("cls")
    else:
        os.system("clear")
def pushp(x, y, t="#", r=True):
    global scnmem
    scnmem += [[x, y, t]]
    if r:
        updscn()
def clrscn():
    global scnmem
    scnmem = []
def xysscnmem(x, y):
    global scnmem
    for i in scnmem:
        if i[0] == x and i[1] == y:
            return i[2]
    return None
def pescnmem(x,y):
    global scnmem
    for i in scnmem:
        if i[0] == x and i[1] == y:
            return True
    return False
def popp(x,y):
    global scnmem
    for i in scnmem:
        if i[0] == x and i[1] == y:
            scnmem.remove(i)
def updscn():
    cls()
    global scnmem
    for y in range(0, 63):
        for x in range(0, 63):
            if pescnmem(x, y):
                d = xysscnmem(x, y)
                print(d, end="")
            else:
                print(" ", end="")
        print()
def pusht(x, y, t):
    lt = list(t)
    h = 0
    for rt in lt:
        pushp(x+h, y, rt, False)
        h+=1
    refscn()
#

tell me if you have any comments, questions or suggestions

tribal path
digital rose
#

I am trying to make an app in kivy, need some help with mapmarkerpopups and buttons
What I want to do is when I press a mapmarkerpopup, a button should appear which when pressed should open a label at the bottom of the screen
can anyone help me with that?

#
#: import MapView kivy_garden.mapview.MapView

MapView:
    lat: 19.2183
    lon: 72.9781
    double_tap_zoom: True
    double_tap_zoom_out: True
    zoom: 12
    MapMarkerPopup:
        lat: 19.289
        lon: 72.95
        Button:
            text: "Bhayandar Pada Plant"
            background_color: 1,0,0,0.65
            background_normal: ''
            on_press: ??
#

the .kv file โ˜๏ธ

obtuse acorn
#

I've been working on a project to simplify / automate PyPi module creation and maintenance with a GUI interface written in tk/ttk/sttk

#

Currently it supports viewing/editing json and toml as well as a lot of plain-text stuff like md/txt/js/css/html

#

Also display images when clicked, any special viewer features you can think of that would be cool to add?

obtuse acorn
#

Btw most of the actions are through context menus like this one

blissful fulcrum
#

Hi!

#

Does anybody know how to get similar looking buttons with tkinter:

#

Best I have is this:

#

But first of all, the shadow is not in the right corner, and second of all, there is no "second border"

vast tinsel
blissful fulcrum
#

Oh... So there's no way to do this with a single element I guess

#

I'll use a frame instead

#

However, how can I make the shadow look so dark and be on the bottom right?

obtuse acorn
#

@blissful fulcrum

import tkinter as tk
win = tk.Tk()
win.geometry("50x50")
outer = tk.Frame(win)
outer.pack(fill="both", expand=True)
button = tk.Button(win, width=15, height=15, text="0", relief="raised", borderwidth=15)
button.place(x=0, y=0, width=45, height=45)
win.mainloop()
#

set your relief to raised and borderwidth to a decently large number

obtuse acorn
blissful fulcrum
#

On a slightly related note, are grids not expandable with tkinter?

#

I guess I could look that one up

obtuse acorn
#

You will get cleaner / more consistent results if you avoid grid and use pack with the occasional use of the place method

#

@blissful fulcrum

import tkinter as tk

layout = [
    ["1", "2", "3", "+"],
    ["4", "5", "6", "-"],
    ["7", "8", "9", "*"],
    ["=", "0", ".", "/"],
]


class ButtonApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        for row in layout:
            row_frame = tk.Frame(self)
            row_frame.pack(fill="x", pady=5)
            for b in row:
                tk.Button(
                    row_frame,
                    text=b,
                    width=3,
                    height=1,
                    relief="raised",
                    borderwidth=15,
                    command=lambda b=b: self.on_button_press(b),
                ).pack(side="left", padx=5)

        tk.Button(
            self,
            text="Clear",
            height=1,
            relief="raised",
            borderwidth=15,
            command=lambda: self._on_button_press("Clear")
        ).pack(fill="x", padx=20, pady=5)

    def on_button_press(self, value):
        print(value)

ButtonApp().mainloop()
blissful fulcrum
#

Wow that's so clean, tysm

dark inlet
#

how do I do this using pygame?

#

pls help me

vast tinsel
#

make a button sprite for pushed and not pushed, and use an onclick async

dark inlet
#

How do I accept input from the user using pygame?

vast tinsel
#

look at the docs

dark inlet
#

Where is it?

#

is it in discord?

vast tinsel
#

no

#

something that could have been found if you had looked it up

dark inlet
#

thnx

#

but even that can't answer my question

vast tinsel
dark inlet
#

But that's not what I need

vast tinsel
#

you wanted things to make buttons

#

from thier core, buttons are just mouse events

dark inlet
#

nope

vast tinsel
#

yes

dark inlet
#

How do I accept input from the user using pygame

dark inlet
#

hmmm

hollow pike
#

hello guys,
I wrote a Tkinter GUI to display the images captured from the webcam on a canvas
a button on the right starts/stops the capture

what I'm doing is:

  • assign to the button (buttonCaptureStartStop) a callback (start_capture) that will prepare and start the capture
  • save the previous callback reference (start_capture) and assign a new callback to detect when the button is pressed (buttonPress), so that the function run using the after method (webcam_capture) knows when it should stop executing

I'd like to reduce CPU usage

  • cap_delay used in .after() is 6ms, which theoretically limits the polling rate to ~166Hz, still a full thread (out of 8) of my i7-8550U seems to be in use (at 3.7GHz!)
  • the FPS measured/reported on the Tkinter GUI can go up to 29.9-30.0, although sometimes the value drops to 20-25 FPS

is this a normal CPU usage? is it because 20-30 images have to be converted to Tk/drawn every second? (I guess the answer is yes?)

the script is located here: https://github.com/alex-fdias/computer_vision/blob/main/webcam_capture_tkinter.py

obtuse acorn
#

Reduced the columns to ones that really matter, the side-bar is now resizable and supports images, various text files, json loading and saving with configurable indents, and project details

#

Last step is git integration, and maybe a diffing system?

proven basinBOT
tulip venture
#

hello guys, i am looking to get some new ideas to build a gui app. it can be anything. I am willing to build someone a gui app so i can learn + u can get something out of it
just have to be an app desktop preferably

chilly needle
somber hemlock
#

Music app will be more focussed on UI design and database viewer will help clear the model / controller side of things (in MVC)

chilly needle
#

yeah music app is a bit of a challenge for me. i'd suggest having functionally for switching tabs (like home tab, settings, discover... etc.) im not a great ui person tbh

azure plover
#

hello
Can anyone here help me with a python scrip that should be running by a HTML button ?

obtuse acorn
#

Like push an html button and some python runs?

#

You might want to check out Flask

digital rose
#

bro im just being ignored like shit

peak spindle
#

I have no clue on how to import TKFileDialog (I fixed it by doing ```py
from tkinter import *
from tkinter.filedialog import *

#

my texteditor works, but I cannot save files

#

These 3 keywords 'dont exist' according to VS code.

#

Does anyone know how I properly import tkinter & TKFileDialog

#

(python3)

short badger
#

i also need to go to 9 questions not just 3

hollow pike
restive mist
#

Hey! Do someone know how to change the window's icon with the customtkinter library?

hot mesa
restive mist
#

I'm using customtkinter

hot mesa
#

oh mb

#

I thought you could still just use the normal Tkinter icon with it

buoyant fulcrum
#

Hi Guys!

wary orchid
granite acorn
#

Is there anybody who knows how I can add external image folders, font folders to bulldozer?

#

I want to make an apk

#

KivyMD

somber hemlock
somber hemlock
somber hemlock
proven basinBOT
#

:incoming_envelope: :ok_hand: applied mute to @severe hinge until <t:1669553353:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

proven basinBOT
#

:x: failed to apply.

proven basinBOT
#

:incoming_envelope: :ok_hand: applied mute to @wintry holly until <t:1669605355:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

digital rose
#

Can somebody help me with Tkitner?
I want to get the output from a for loop displayed in my GUI, any tips how to do it? I created Text widget, but my output come out when for loop is over, and i want it to be displayed in real time.

short badger
#

can i have grouped radio buttons

#

in tkinter

short badger
#

and then set text to output (if im wrong im sorry and someone correct me ill delete messages)

glossy frigate
#

what would be the best python gui module to learn for relatively simple applications?

#

would pyqt be more useful to learn than tkinter?

short badger
#

all i can say is i know with certainly tkinter sucks imo

proven basinBOT
#

:incoming_envelope: :ok_hand: applied mute to @static sequoia until <t:1669651249:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

sleek hollow
#

I'm stitching together 2 icons to display on a QListView's decoration role, but for some reason the background of the stitched image is very noisy. The images are stitched nicely, but does anyone know what might be causing this noise?

#

My guess it has something to do with transparency?

#

Found painter.setCompositionMode(painter.CompositionMode_Source) which cleans up the noise to at least be black (still not transparent though). I can deal with that though, haha

buoyant fulcrum
#

Hi Guys! I'm working with tkinter.
I have a main window, but I want a toplevel window to open on my second screen.
How do I make a tkinter window open on my second monitor?
Thank you

somber hemlock
#

I forget the name

buoyant fulcrum
#

if you have a loop, couldn't you just config the label?

#

or call a function that does?

somber hemlock
#

It will update only once at the end of the loop

buoyant fulcrum
#

ahh without time.sleep

somber hemlock
#

Don't use time.sleep

buoyant fulcrum
#

I used that to make mine update every 0.05 seconds

somber hemlock
#

Nor .after is needed

fossil copper
#

Hello, I get this error

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Python310\lib\site-packages\customtkinter\widgets\ctk_button.py", line 377, in clicked
    self.command()
  File "C:\Python310\lib\site-packages\pymongo\message.py", line 370, in get_message
    request_id, msg, size, _ = _op_msg(
  File "C:\Python310\lib\site-packages\pymongo\message.py", line 673, in _op_msg
    return _op_msg_uncompressed(flags, command, identifier, docs, check_keys, opts)

(There's more)

While running the below code:

https://pastebin.com/gv7nSPdv (Admin class part)
https://pastebin.com/qXpKuAHi (Tkinter Part)

#

Please ping me with any answers.

proven basinBOT
#

:incoming_envelope: :ok_hand: applied mute to @hearty hazel until <t:1669675464:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

proven basinBOT
#

:incoming_envelope: :ok_hand: applied mute to @brisk iris until <t:1669679575:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

mighty frigate
#

@sleek hollow I assume you've painted the image yourself. Have you paint the background also ? This isn't something I've seen before, looks like a random background to me

short badger
#

can you group radio buttons in tkinter

#

i need to have 36 buttons

sleek hollow
sleek hollow
short badger
#

and instead have 9 with buttons in groups of 4 for that purpose, not just for the var and values

mighty frigate
#

@sleek hollowcould you show me the code pls

smoky needle
#

Hi, i am currently trying to make app in PyQt and i want to have framed window, without title bar, but still have resize functionality like other apps (e.g. if you drag it on side, it will resize, resizing via cursor at all, etc.) How can i achieve that?

Currently i have this code for losing frame but that is not what i want

self.setWindowFlag(Qt.WindowType.FramelessWindowHint)
mighty frigate
#

@smoky needle I believe there's no default titlebar

#
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys

app = QApplication(sys.argv)

mainwidget = QWidget()
mainwidget.setStyleSheet("background-color: red;")

mainwindow = QMainWindow()
mainwindow.setFixedSize(400, 600)
mainwindow.setCentralWidget(mainwidget)
mainwindow.show()

app.exec_()
#

confirmed : no titlebar by default

smoky needle
mighty frigate
#

iirc you can choose to use the window manager or not use the window manager

#

but you can't choose what part of the window manager you want to use and which part you want to remove

smoky needle
mighty frigate
#

this is what you're already doing

#

while incomplete, that's the right idea

#
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
import sys

app = QApplication(sys.argv)

mainwidget = QWidget()
mainwidget.setStyleSheet("background-color: red;")

mainwindow = QMainWindow()
mainwindow.setFixedSize(400, 600)
mainwindow.setCentralWidget(mainwidget)
mainwindow.setWindowFlags(Qt.WindowType.ToolTip | Qt.WindowType.FramelessWindowHint)
mainwindow.show()

app.exec_()
#

but then you loose all features provided by the OS window manager

#

that means you'll have to write your own drag and your own resize, for example

spring sinew
#
import sys

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPainter, QPixmap
from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow

class MainWindow(QMainWindow):
  def __init__(self):
    super().__init__()
    self.label = QLabel()
    self.canvas = QPixmap(400, 300)
    self.canvas.fill(Qt.GlobalColor.white)
    self.label.setPixmap(self.canvas)
    self.setCentralWidget(self.label)

  def mouseMoveEvent(self, e):
    pos = e.position()
    painter = QPainter(self.canvas)
    painter.drawPoint(QPointF(pos.x(), pos.y()))
    painter.end()
    self.label.setPixmap(self.canvas)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

I generated a small window where I can draw points by pressing down the mouse button and moving the mouse. I want to be able to draw without having to press down the button first. I found out that you need .setMouseTracking(True) for that. I have no clue how to actually implement that though. From how I understood it, self.setMouseTracking(True) in the initialisation of the MainWindow class should do the trick but it's not working. Neither did self.label.setMouseTracking(True).

mighty frigate
#
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.label = QLabel()
        self.canvas = QPixmap(400, 300)
        self.canvas.fill(Qt.GlobalColor.white)
        self.label.setPixmap(self.canvas)
        self.setCentralWidget(self.label)

        self.label.setMouseTracking(True)
        self.setMouseTracking(True)

    def mouseMoveEvent(self, e):
        pos = e.pos()
        painter = QPainter(self.canvas)
        painter.drawPoint(pos.x(), pos.y())
        painter.end()
        self.label.setPixmap(self.canvas)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

@spring sinew

#

reason : the moues isn't actually over the mainwindow, but over the label. That's why you have to enable the mouse tracking for the label

#

but this won't be enough : if you don't enable the mouse tracking for the mainwindow too, the event won't be transmitted from the label to the mainwindow

spring sinew
#

I guess your first new line should be self.setMouseTracking(True) though?

mighty frigate
#

am sorry what

spring sinew
#

You added self.label.setMouseTracking(True) twice.

mighty frigate
#

ah indeed, too fast of a refactory

spring sinew
#

But you said you'd need to enable it for the main window and the widget

mighty frigate
#

corrected

#

that's what the 2 last lines do

smoky needle
mighty frigate
#

p.s: using eventFilter can help you debug and understand those kind of problem

#

@smoky needleI told you twice already, to my knowledge you can't. Because the title is handled by the window manager, not by Qt.

#

at least not with QtWidgets

spring sinew
mighty frigate
#

@spring sinew a small example to illustrate

import sys

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.label = QLabel()
        self.canvas = QPixmap(400, 300)
        self.canvas.fill(Qt.GlobalColor.white)
        self.label.setPixmap(self.canvas)
        self.setCentralWidget(self.label)

        self.label.setMouseTracking(True)
        self.setMouseTracking(True)

        self.label.installEventFilter(self)

    def eventFilter(self, target: 'QObject', event: 'QEvent') -> bool:
        if target == self.label:
            print(event)
        return super().eventFilter(target, event)

    def mouseMoveEvent(self, e):
        pos = e.pos()
        painter = QPainter(self.canvas)
        painter.drawPoint(pos.x(), pos.y())
        painter.end()
        self.label.setPixmap(self.canvas)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
#

@spring sinew one other thing : if you want to draw lines instead of dots, what you could do is memorise the last position of the mouse, and draw a line from the last position to the new one on each move

sleek hollow
# mighty frigate <@143878644169834496>could you show me the code pls
#Images I want to combine
Valid = QtGui.QPixmap(':/confirm.png')
Invalid = QtGui.QPixmap(':/error.png')

#Pixmap to hold the resulting image
combo = QtGui.QPixmap(40, 20)

#Painter used to paint on the pixmap
painter = QtGui.QPainter(combo)
painter.setCompositionMode(painter.CompositionMode_Source)

painter.drawPixmap(0, 0, Valid)
painter.drawPixmap(Valid.width(), 0, Invalid)

Dummy = QtGui.QIcon()
Dummy.addPixmap(combo)
#

In the meantime, I'm likely just going to switch from ListView to TableView and use the columns to display the images I want instead

mighty frigate
#
painter.fillRect(combo.rect(), Qt.transparent)

untested, but somethign like that

sleek hollow
#

do that before any drawing?

mighty frigate
#

before the 2 draw()

#

what class is that in ?

sleek hollow
#

it's just part of my inherited QAbstractListModel class. It's an absolute mess because I was just testing with it and I was going to properly implement once I knew the logic worked

mighty frigate
#

alr

#

if you want to add more UX features, usually you want to implement a delegate

sleek hollow
sleek hollow
#

but that seems to be the common reccomendation

mighty frigate
#

yeah model/view is a bit overwhelming in Qt

sleek hollow
#

It's so powerful though. It made this current task a breeze

mighty frigate
#

check if i'm not mistaken and the rect() is actually the correct rect, like (0, 0, 40, 20) or something

sleek hollow
mighty frigate
#

sounds alright

sleek hollow
#

I think the tableview solution is better anyways for now. I can keep adding more columns if I need more info icons

mighty frigate
#

what are you trying to accomplish again ?

#

sorry I have the memory of a fish

sleek hollow
#

I have a list of items and each of them has a view boolean attributes. I want an icon to represent those states of each item

mighty frigate
#

ok

#

so basically

sleek hollow
#

Right now I'm still just using an icon for 1 bool (the merged was a bust), and I'm colour coding the text for a different bool

mighty frigate
#

| name button1 button2 button3|
| name2 button1 button2 button3|

#

etc

sleek hollow
#

it's a list of assets for a game. The icons are meant to represent what stage they're at (has a model, has textures, has animation info, etc)

mighty frigate
#

ok

#

so yeah, listmodel listview and delegate

#

that's probably the best

#

tableview, I'm scared about the button press handling

sleek hollow
#

another button handles loading from selection

sleek hollow
mighty frigate
#

the row of a table or a delegate ?

sleek hollow
mighty frigate
#

that actualyl quite close

#

are you afraid of C++ ?

sleek hollow
mighty frigate
#

welp

#

ok I'll need a sec

sleek hollow
#

I kinda get the gist reading the c++ docs for qt at least since the class/methods are all the same

#

but yeah, I get a bit lost in the structure

#

I guess my main question is where does the delegate live in relation to all the data?

mighty frigate
#
model = SomeModel()

delegate = SomeDelegate()

view = SomeView()
view.setModel(model)
view.setDelegate(delegate)

^ the basic usage

sleek hollow
#

I have my abstract list class that forms the model (holding my game asset objects), and that gets plugged into my listview

#

so is it QItemDelegate I inherit from for the delegate?

mighty frigate
#
class SomeDelegate(QStyledItemDelegate):
     def paint(self, painter, option, index):
          opt = option
          self.initStyleOption(opt)
          
          status_pixmap = index.data(MyCustomRoles.StatusRole)
          if not status_pix.isNull():
              status_icon_rect = QRect(opt.rect.x(), opt.rect.y(), status_pixmap.width(), status_pixmap.height())
              opt.rect.translate(status_pixmap.width(), 0)              
              opt.widget.style().drawItemPixmap(painter, status_icon_rect, Qt.AlignCenter, status_pixmap);

          opt.rect.setWidth(self.sizeHint(opt, index).width());
          super().paint(painter, opt, index);

^ this is the paint function of the delegate. Every item in the list is painted by it.

Here we're retrieving a pixmap representing a status; and if it exist we're modying the rectang where the item would normaly be displayed to make room for the new pixmap, and we're drawing it. After that, we let the default implementation of QStyledItemDelegate take care of the rest of the drawing.

#

so, in that function you have the painter (which is a QPainter) you already saw that one

#

option contains some datas related on the visuals : is the index selected for example

#

and index is the index from the model, you should more and less know what this is

#

this code also uses something I told you before about custom roles, if you remember

sleek hollow
#

yeah, there's predefined roles for certain operations but you can also define your own

mighty frigate
#

yes

#

this code draw the pixmap on the right of the item tho, not on the left

#

but you get the idea

sleek hollow
#

so ideally I would write a method that packs up all my bools like [0, 1, 1, 0, 0] and it knows which images to stitch together based on that?

mighty frigate
#

this isn't what I would do

#

I would have one role for each bool

sleek hollow
#

oh

mighty frigate
#

retrieve those datas in the paint()

#

and draw each pixmap one by one

sleek hollow
#

but then how would it refer to which image to draw?

mighty frigate
#

depends on you