#user-interfaces
1 messages ยท Page 3 of 1
pyside6 would be the best and easiest to work with
i agree, but my team wont listen
what they want?
: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.
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
@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
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?
@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
I don't get it...does PyQt5 have anything like "gui" in its library that pyqt6 does not have?
... You already imported QtGui, what more do you want
or is it a whole different library idk i am kinda new to interfaces
@swift mountainwhat are you looking for exactly
Qt never had a gui library afaik, it does have a QtGui library tho.
wait i figured it out..oh lord i am dumb...thats actually a python file named "gui"
Does anyone know how using tableview in tkk can make it so when a row is selected, a button font is changed?
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?
Setting a default doesn't do the same thing, because it would still allow the user to override the value. I'd equate action='store_true' to action='store_const', const=True instead. I'd guess it just exists as a shorthand for a common use case.
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?
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)
Does anybody knows how to crop a QGraphicsVideoItem? https://stackoverflow.com/questions/74174919/crop-qgraphicsvideoitem
I finally got it!
https://stackoverflow.com/a/74175532/11760835
This was a MASSIVE help! Thank you so much! Sorry for not replying sooner, I was traveling
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
[pyqt]Hello, how to change the value of a QSpinbox to infinite (Well not actual infinite just very long).
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
can't just lambda it?
You mean, like lambda: actual_function?
Hmmm I guess that could work
[pyqt] Anyone who can help here? #help-cake
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
Myself Kartavya Shukla Welcome you to the newest era of code with this website as Novfensec.
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...
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.
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.
Imagine Python then
Anyone familiar with pyqt pages and tabs for a question?
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
Often times, you may need to place matplotlib charts on a tkinter GUI. In this short tutorial, you'll see the full steps to place your charts on the GUI.
Its Not xp. 2000 maybe?
What?
I basically have this for the moment
and I want this
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
my bad
ok
looking for someone to write a bit of code for me? need to have experience with threading and UIs
dm for more info
๐ฅบ
inserting matplotlib frame into tk? TkAgg
Any kivy guys 'round?
Just woke up, trying to learn kivy, not sure if I can be of any help...
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.
ok
what are you using to create and start your thread
there's a few different way to do it wih Qt
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:
are you subclassing QObject and moving it to a QThread ? Are you subclassign QThread ? Are you using QRunnable and QThreadPool ?
QObject and QThread ok
yeah right Qobject and qthread
show me Worker pls
idc about the urn function
my bad
ok, emit is located inside this bug run function in several points. One point is this one: (Give me a moment)
ok I trust you
when you run your code in debug mode, is there anything showing in the console like "cannot connect signal" blablabla ?
No, the code runs fine. The problem is that the created threads in the end of the function are not being deleted.
we'll see about that
add
def __del__(self):
print("--- Worker destroyed")
in your worker class
and tell me if the message is printing
no the message is not printing
are you in a run mode where messages actually get printed usualy ?
Yes I am in run mode. These are the messages
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
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?
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
I have checked the documentation where it says that:
oh this is a python function
Yeah.
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
Ok. I can see your point.
in that regard I have more faith in QThread::isRunning
Yeah, but wont I have in the future a problem with the memory if too many threads are created?
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
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.
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
Let me check that, but I just checked the signal is indeed emitted. So maybe this is the problem.
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
but we're going somewhere, the signal is emitted but isn't received somehow
Ok, this is the piece of code, the first line what it does when the worker finishes quit the thread
Ok, so I have to check if the signal is received where I want. Understand.
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 ?
ok
self.w is the widget
it's fine then
This function is running btw
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
One moment I want to understand this clearly.
@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. ๐
I have one question and I wont spend any more time. The event loop if the run function in the Worker class?
don't bother with the event loop. If you have a QApplication and you're not destroying it, you're fine
Ok. I appreciate once more the help. Dont hesitate if you need something. Thanks a lot!
@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?
@spark tinsel ennoeitai an mporw na boithisw
Thanks!
@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
That's the thing I can't seem to find how to use it in my case
I try to call the figure object from my class Conway and then use the TkAgg on that but it doesn't work
Ok, so your opinion is that the thread is actually deleted or no?
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
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
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
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.
@somber hemlock
Where do you want it placed tho?
On the desktop at the top right?
at the top middle
how would I make the shape without making a window?
Idk about rounded, but tk.Tk has an attribute for that non bordered
Search on google, there will be stackoverflow results
do i just look up "tkinter shape without seperate window" or something? what i am looking up is not showing anything
Search tkinter borderless window
Then search tkinter rounder window
Or search the second directly
Can't really notice it with your black IDE theme going on
Good
i need to make it smaller, and it looks rigid
oh yeah so how would i center it?
Well you can make it as small as you want can't you
the rounded thing is made with length and width
Grab the screen coords and offset your widgets controls by those amounts
why the sides doingf that ๐ญ
Well it looks like the corner radius is larger than 50% the dimension of the window.
And TK do'nt have great code for handling that case.
I am once again asking for your technical support
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 ?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I want to make it like this
- How do I add the circle(input & output) ?
- How to check if a node is connected ?
- Make a clone of a node when I click add gate button ?
Assumin you are using canvas?
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 
I'm using pyqt6 and wanted to know how to make a QStackedWidget resize to fit the content of the currently displayed widget exactly
Nothing I do seems to be working..
Please, help
PyQt5, how do scrollable list/table kind of [image text]
like on youtube
@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()
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
you're the one in control. What's stopping you from creating a function that insert your whole line cell by cell
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
its on table widget too?
@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.
how to block changing elements text (content) in a table in QTableWidget?
Why do you have a button for clearing fields?
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
To delete the values on entry
Alright thanks
Well i am going to add more buttons
There's no need to put it. If somebody does an error they can clear a field by backspacing as well right?
You can add a scrollbar then, don't try to fit it all in a single screen
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.
Or is there a way to expand QLabel somehow?
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
How do Signal for Entire Row Selection in QTableWidget in python pyqt5?
like this https://stackoverflow.com/questions/3144418/signal-for-entire-row-selection-in-qtablewidget
?
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)
Instead of your if/else statement at the bottom, you can simply do Cbrow += 1
and then Cbcolumn should be 2 when you initialize it if you want it to line up in the center rather than underneath the Marital Status label.
anyone that can help me with a stopwatch function inside qt designer?
Check in flag: "horizontalHeaderStretchLastSection" in header section
it only counts to 0.1 then stops, my conclusion is that it only runs once instead of getting updated, problem is I don't know how to fix it
here's the code
im go to try it
How set...HeaderItem(QHeaderView)?
its possible?
In QTableWidget
I can't figure out how to do it right
how do I stop this from resetting its size everytime something changes in the designer
it's qtextedit
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.
The QTimer class of the PyQt library allows users to create a digital clock, time counter, progress bar, and more. This tutorial shows you how to use the QTimer class to create time-related PyQt applications.
thanks, also, would you happen to know why
@Slot()
def submit(self):
self.thread_manager.start(self.submit)
print("Submitted")
which is attached to a .clicked.connect
gets run continously when I click it once, just starts spamming prints in the console forever
thread_manager is just self.thread_manager = QThreadPool()
Sorry idk about threads yet.
I figured it out
Are you not able to find that flag in header section??
Tick that checkbox
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?
What UI framework/toolkit/thing would be best suited to making a schematic editor?
is there a way to increase the width of this white line in pyqt, these are 2 styled QPlainTextEdit widgets side by side
try using custom tkinter
you know any good fork of tkinter?
yeah, it's called custom tkinter
oh sorry lol, didnt think that actually was the name. thx :) il try it out
Qt is used by a lot of such detailed complicated apps, like IDA for example
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
Hello, Can I use vpython and tkinter libraries together? Is there anyone who can help?
vpython?
What the v is that?
do you mean cpython?
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)
how i can do this?
@thick apex the documentation says both modes can't work together :
https://doc.qt.io/qt-6/qheaderview.html#ResizeMode-enum
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
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_())
This only last section
so you want the same behavior but not for the last section; only for the first one
correct ?
For all
by default the columns are NOT stretched evenly to the QTableWidget borders, but they can be resized with the mouse?
I want columns to stratch and after enable to mouse resizing
@mighty frigate I have only stretch, how do resizng after?
I just asked, I think there may not really be an answer, so don't think I'm rushing you, I'm sorry
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
time is money
it is possible to make the rightmost edge of the header attached to the right side of the widget?
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?
@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
In the code snippet provided: Move a paper across the screen.
In my actual problem: Simulate rocks, papers and scissors like in this video: https://youtube.com/shorts/D86dl1Hc5uI?feature=share
Can't remove embeds on mobile right now
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
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
give me a minute
The snippet is actually really close to my actual code, just a tad simpler
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
Thank you, I'll look at it after taking a nap. Trying to fall asleep with a prostate infection is quiet tedious though.
ow well, good luck and good nap
Kind of a longer nap, but at least now I'm fully awake.
The code you sent appears to be producing exactly what I was looking for. I'll look into how it actually works. Thank you so much.
np
@winged solar if you're new to Qt, you def should take a look at the signal/slots feature
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
Do I need the Qt 5.15 LTS?
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?
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
okay, I'll just go with that x)
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
got it, thanks
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 ๐ฌ
both are sufficient for normal stuff
what did you have in mind?
Not a lot
Qt is fairly stable to break too much API
But that's what release notes are for
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? ๐
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")
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
how Make QRegExpValidator to string contains only '-' or integer num from 1 to 1000
?
Then you don't need the newest book either ๐
Tons of applications still use 5.15 to save space. Newer qt releases are heavier
heya, does TUI's count as something i could ask about in this channel?
Since the channel description talks about multiple TUI libraries, I assume yes
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
You can disable and enable the button by using btn.config(state="disabled") or use a bool variable inside button's callback to store its state
thanks mate
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()```
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?
does anyone know using textual, how to make it autoscroll?
@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
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
@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
is it hard to use
arguably yes
tkinter is very simple to make a basic ui and get it going
any good tutorial (preferably text based)
are you the kind of guy that reads documentation ?
not really, that stuff confuses me
well you'll probably struggle then
unless it is written really well so that it is easy to understand
i learnt tkinter from a book lol
there's some key concept you need to know and understand when you work with Qt. Iguess it's true for all libraries tho
whats the qt docs?
best advice I can give you : the official Qt documentation (in C++) is very nice
use it
ahh ok
i do a little coding in c
mostly c#
but python is my main coding language
tbh it doesn't really matter, the API is the exact same in C++ and Python
ahh ok
the syntaxe is a bit different but it doesn't change anything
is pyqt web based?
i need to be able to run it as an exe that can be downloaded very quickly
well I guess that's on you
so a signal is the start and the slot is the destination
yessir
yeah, thats how i build it
exactly
can i download qt with pip or is it a standalone app
both
with python you can use pip
in Cpp you actually have to download Qt yourself
any docs specific to python version. id like to have a read of them too
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?
Hmm is something wrong
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.
hope that helps, i am useless with virtual env's as i never use them
Ok it worked without the virtual env as well๐
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
I work on KISS (Keep It Simple Stupid), When making apps for people, design it for some one who does not know how to use a pc (not to dumbed down but)
Is this a python library?
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
I wouldn't know I only use the official one
ahh ok
KISS?
Yeah
how old are you............
i used to use tkinter but ima try my hand at pyqt
Qt does a lot more than just UX too
...... once i have finished this damn assignment
what else?
SQL, filesystem, web related things, networking, regex and a lot more
networking, OoOoOoOo
Can tkinter solve this?
well in languages like C++ it's a good thing because you don't install a lot of dependancies usually
are the modules available in python as well? cos having bluetooth seems useless but cool
but that's not the case with python.
like, if you need to do some networking task, you can simply use request
for example
kivy finally added 3.11 support, looks like wheels will come next release
Can someone help with with tkinter?
How do i insert all the content from a txt file into a tkinter Listbox?
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?
What's the fastest or best gui to learn?
tkinter is pretty simple
wouldnt say best
Kivy is good
If you can deal with the fact that it has no type hints
Is there a gold standard of CLI format converter design that is worth using as reference when building a new one?
do you mean fastest when running, fastest when learning, or fastest to build with?
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
Kivy is not good at mobile, its only supported
Best consider it an alpha for android or ios
https://youtu.be/ic0PnF04N-Q
there is also this ^
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 ...
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.
QLayout::addWidget can take an alignment as params iirc
check the QGridLayout documentation
Thank you that worked.
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
Is flutter better?
miles ahead
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.
(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.
How can I do closeEvent in PyQt5 without using QMessageBox (for the X button at the top of the window)
One more thing...is Django best framework for websites or the is another language better?
Please tag when you answer thank you
You would override the function within your subclass for the QMainWindow or QObject
how so
I'm using this but it doesn't work ```py
def closeEvent(self, event: QtGui.QCloseEvent):
print("Check")
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
I really don't understand and I can't ๐ฆ Would you look if I threw you open source codes?
Yeah, if you have code post it~
Hey @copper jackal!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
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
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
but it did happen
What happened?
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
both the widget defined above and below
I just called the other widget a temp name widget, you can change it to something else. But it's also different from self.widget
is it because of the variable of _translate that he didn't read this place?
not work ๐ฆ
Is Eel good for GUI development?
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?
modern TUI
This had some hype around it a few months ago, but I haven't had a chance to use it yet. https://www.textualize.io/
Holy crap textualize actually has documentation now
I've been using it just via source code reading (total pain in the ass)
Is anyone familiar with QThread?
I'm having issues creating a loading screen as shown in #๐คกhelp-banana
Any help would be great.
guys how to make tabs in tk?
any kivy user here?
@fiery blade Yea I use it
there is a way to show pages in a tk window? like a website?
can someone pls help me
hello?
could anyone with access to the newest martin fitzpatrick Qt6 book share the pdf with a porr dude from 3rd world?
oh yeah seen u various times on github server
does anyone know how to make ascii like this
from where did you get that screen shot?
a friend of mine sent me
that looks like the ASCII art was probably created by hand
this box and ascii looks decent
Yeah
oh
thats too much work then
There's a few tools that can do that, I just can't remember any in particular
I found this article on Ascii Art Gens
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
oh thanks!
yeah I can color it
just need to get the text
in the ascii
(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()
nurses_2 turn any image into colored braille:
you need to add full path of the .ico file
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?
emit the result from the thread to a callback in the main
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.
hmm, interesting, lemme check how that works..
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 ?
I was trying to just submit a callable to a python threadpool
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
@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()
That works as is?
It does.
I don't have any direct subclasses of QObject, no
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
I assume that's what's used in this horrible, probably autogenerated-from-C++-docs snippet
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
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.
nice when stuff just works out like that
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
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
For the ASCII art, you can use that generator, and for the coloring, perhaps you can use Blessed or just color each column individually
Hello
This is my website, I want to improve it. Can yโall comment and lemme know what should be changed please? What are your thoughts?
is there a way , i can set up a shortcut like alt + f5 , for opening a tkinter app?
That's not a tkinter thing you need to setup outside
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?
people still use the floppy disk as the save icon
take away what you will from that, haha
Is there a module for an ascii text art game user interface?
hey guys
are you interesting about converting small images to python code ?? ๐
Hey @raw sedge!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
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:
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
rich? or textual. looks like bpytop is using ansi codes directly
Hello , can I get help with GTK here?
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' });
}
Ok, now my problem is that the event target I'm getting is for the icon inside my button.
fixed
Is there a module for a terminal like system but without all the settings, selection, resizing, etc.?
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
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',
)
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.
Is there a module for a terminal like system but without all the settings, selection, resizing, etc.?
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)
Perhaps #async-and-concurrency is what youre looking for @ebon bison
Use a queue to pass messages from / to the UI thread
pls see the message and help with the issue:
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
I've run into the exact same issue and it's a pain for sure! I've never gone as far as implementing a proper solution (I'm the only one using the tool), but you would need to get your monitor DPI and use it in some sort of ratio calculation for your widget sizes
I know how to get DPI with PyQt but not really sure with tkinter
@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
Yeah that seems way less head-achey!
Ok so it's not only me ๐ I found also a hacky solution.
On startup a window is created, set to full screen, save x&y, destroy window. Using those values I calculate the width& height for my usecase, works I guess
sadly it doesn't work in all cases
One downside is this makes a small window flash up shortly.
for example, you can customize the text size on windows
the resolution alone isn't a good enough indicator
Hm have to check that. As I mentioned I just realized this due to 100% vs125% scaling. Both monitors are 1080p bit the laptop looks so much different
to solve the windows flashing, you could use another lib to get the screen size
Yeah probably easier. I found something on Stackexchange but I think that was for Linux. I'll look how to get the size, probably with some
os.getscreendimensions```
Or similar
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:
Ive been looking into that, do you know of any basic examples of such implementation? I wanna communicate main thread and thread I create
There's some very nice answers on this topic on Stackoverflow. Let me see if I can find one.
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?
If you run into those kinds of problems, just check for plugins for the language/framework you are using. Popular ones almost always have a good plugin.
Try this library. I suppose you have already installed Pylance, its like the most default thing VSCode does when you open a Python file
!pip PyQt5-stubs
Wish kivy had type hints...
what do you guys think about this scrolling i added in my app?
Considering tkinter has no animations, this is quite good ๐
thx , i want to do this with 20 buttons , i dont think it will be as smooth as this after that
Well this one looks smooth enough to me. But tkinter is entirely CPU rendered ig, so yea
Tkinter is quite bad perf-wise. You might have some better luck with canvas ig
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.
On linux you need to install tkinter separately
sudo apt install python3-tk
If u r talking about making it like desktop app , u can do it with packege makers like , pyinstaller
Yeah I want to make it into an installer.exe file that people download and then they can just use it. Just like any other software you download..
Than use pyinstaller, u can install it through command prompt
Using pip
Ok thx, and the user doesn't need pyinstaller to install my application right?
It will just be a setup.exe file that includes everything needed?
Yes ,user can just use it as normal desktop app
Ok thx man
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
Thanks, yeah I'll be using customtkinter and I read that --onefile doesnt work with that instead it says to use --onedir
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?
Just modify the .ui file and convert it to .py again 
You can manually modify the code in .py file as well
Yeah but like I added lots of backend code into that file..so even if I edit the original .ui file and convert into .py again then I'll have to write the backend code all over again
Backup the existing one, merge back the changes
You shouldn't even be touching the .py file created by qt, you are supposed to write your code in a different module
got it! thanks
Is there any way I can replicate that network activity graph in python? apart from matplotlib
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.
@spring sinew Qt devs recommand using Qt Designer
I personnaly hate it and I don't use it
Is there any reasoning behind their recommendation and your hate?
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
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
Rather use tkinter tbh pyqt is meh
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
Isn't that problem resolved by just not using Qt Designer and entirely writing it yourself?
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
PyQt is, afaik, way more capable and has way more features than tkinter
it depends on your need I guess
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?
you need to specify what lib you're using.
Sorry, tkinter + custom tkinter
People use pyqt for real apps ๐
Those that already use qt for desktop apps would find pyqt easy
does anyone know where to find simple practical example of something made with tkinter (only the original modules no extensions or anything)
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?
Can you share the code you've written that isn't working as expected?
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
Haha is that really the issue?
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
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
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?
depends what exactly and how exactly you're trying to do it
@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
I haven't seen this pack(), maybe that's my issue?
pack is just another way of adding something to the window
place and grid are the other ways
.rp tkinter
Here are the top 5 results:
I recommend that first realpython tkinter article. That's where I first started and it helped me out a lot
Much appreciated!
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)
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
Yeah. That's what I've been doing for the past 3 years
@sleek hollow QSortFilterProxyModel does exacly that : https://doc.qt.io/qt-6/qsortfilterproxymodel.html
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?
You will call self.grid only once, I don't see an issue. You can also override the grid() method of MainFrame to separate the placement code from widget initialisation
Not quite sure I follow how this is used. So how would I apply to my model to show only the objects that have a certain bool attribute as True?
@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
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.
ThAt'S iLlEgaL
@spring sinew afaik Qt already check for this. You can verify for yourself by browing the Qt code directly
Is there a downside to the approach I use with a buffer list and manually do some filtering?
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.
Though this bug report https://bugreports.qt.io/browse/QTBUG-11539 and it being fixed makes me think that it does the check on Linux as well.
@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.
Good to know. I'll have a look at the sortproxy when I'm at my pc next. I appreciate the help as always!
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
nvm i got it
dpg.set_viewport_max_height(HEIGHT)
dpg.set_viewport_max_width(WIDTH)
Thanks for the tips!
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.
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
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 โ๏ธ
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?
source? i would like this
I gotta get the profiles system (for pushing to testpypi / private repos) finished and add support for a project having multiple submodules before I release this but when it's made public it will be at https://www.github.com/AndrewSpangler/py_project_manager
Btw most of the actions are through context menus like this one
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"
try putting two buttons on top of eachother
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?
@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
??? that's a bad recommendation, this is totally possible with just a button + config
Oh wow, tysm!
On a slightly related note, are grids not expandable with tkinter?
I guess I could look that one up
any help?
I really recommend the pack method after about 4 years of daily tk use prototyping etc
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()
Wow that's so clean, tysm
make a button sprite for pushed and not pushed, and use an onclick async
How do I accept input from the user using pygame?
look at the docs
But that's not what I need
nope
yes
How do I accept input from the user using pygame
hmmm
bruh help me pls
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
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?
Hey @vast tinsel!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
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
two apps that i've built which are sort of fun are
-Music app
-Database viewer
Nice two examples
Music app will be more focussed on UI design and database viewer will help clear the model / controller side of things (in MVC)
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
anybody?
hello
Can anyone here help me with a python scrip that should be running by a HTML button ?
bro im just being ignored like shit
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)
i also need to go to 9 questions not just 3
maybe there's simply no one knowledgeable or even interested enough to reply to you
no one here is at fault, help is voluntary
Hey! Do someone know how to change the window's icon with the customtkinter library?
from tkinter import *
window = Tk()
window.geometry("1080x720")
window.resizable(False, False)
window_icon = PhotoImage(file='icon.png')
window.iconphoto(True, window_icon)```
I'm not using tkinter
I'm using customtkinter
Hi Guys!
you can research building a calculator with tkinter or a user login interface
Is there anybody who knows how I can add external image folders, font folders to bulldozer?
I want to make an apk
KivyMD
Its still the same in tkinter
do
import tkinter.filedialog as tkfd
and then use it everywhere like
tkfd.asksaveas(...)
tkfd.askopemfile(...)
This is better than a star import
Also showerror is from tkinter.messagebox
Where is this HTML button? On a website or stored locally?
๐
: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.
:x: failed to apply.
: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.
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.
empty label i think right at least thats how it is in c#
and then set text to output (if im wrong im sorry and someone correct me ill delete messages)
what would be the best python gui module to learn for relatively simple applications?
would pyqt be more useful to learn than tkinter?
all i can say is i know with certainly tkinter sucks imo
: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.
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
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
Call tkinter.update_idletasks() inside the for loop
I forget the name
if you have a loop, couldn't you just config the label?
or call a function that does?
Yes but it won't get updated in real time
It will update only once at the end of the loop
ahh without time.sleep
Don't use time.sleep
I used that to make mine update every 0.05 seconds
Nor .after is needed
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)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Please ping me with any answers.
: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.
: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.
@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
It's painter + pixmap and I'm using it to draw 2 pixmaps together. I didn't do anything special to handle the background though
Yes, you can assign an IntVar to any button you want to be part of the same group
sorry, i mean like to where i can cut down on code instead of having 36 lines formatting buttons
and instead have 9 with buttons in groups of 4 for that purpose, not just for the var and values
@sleek hollowcould you show me the code pls
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)
@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
That is not what i want, i want to remove title bar, but have still a frame around my app
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
How to choose to use window manager?
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
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).
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
I guess your first new line should be self.setMouseTracking(True) though?
am sorry what
You added self.label.setMouseTracking(True) twice.
ah indeed, too fast of a refactory
But you said you'd need to enable it for the main window and the widget
And how can i keep that OS window manager but remove title bar?
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
I will look into that. Just playing around with some basic functionality for now. Thanks for the help
@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
#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
painter.fillRect(combo.rect(), Qt.transparent)
untested, but somethign like that
do that before any drawing?
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
alr
if you want to add more UX features, usually you want to implement a delegate
Didn't seem to have any affect on it. Even tried commenting out the setCompositionMode
Yeah, I'm still fairly new to model view in general so wanted to see what I could get away with before diving into delegates
but that seems to be the common reccomendation
yeah model/view is a bit overwhelming in Qt
It's so powerful though. It made this current task a breeze
check if i'm not mistaken and the rect() is actually the correct rect, like (0, 0, 40, 20) or something
PySide2.QtCore.QRect(0, 0, 40, 20)
sounds alright
I think the tableview solution is better anyways for now. I can keep adding more columns if I need more info icons
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
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
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)
ok
so yeah, listmodel listview and delegate
that's probably the best
tableview, I'm scared about the button press handling
The only thing I need to worry about for that is selecting a row
another button handles loading from selection
so what does delegate allow me to do icon-wise?
the row of a table or a delegate ?
I basically would expect the table view selection to behave exactly how the list view would
Never used it
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?
model = SomeModel()
delegate = SomeDelegate()
view = SomeView()
view.setModel(model)
view.setDelegate(delegate)
^ the basic usage
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?
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
yeah, there's predefined roles for certain operations but you can also define your own
yes
this code draw the pixmap on the right of the item tho, not on the left
but you get the idea
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?
oh
but then how would it refer to which image to draw?
depends on you
