#user-interfaces
1 messages Β· Page 14 of 1
Yikes @mighty frigate
what's your point ?
wtf, ultimaker cura is completely written in python (with PyQt), thats very cool
3d printing software
even the 3d render is done in python, didnt know it was capable of that
No, it has to occur during a callback of some sort. All GUI functionality will occur in function calls once the window is shown
^ either delay your .get() in a thread or do it on a callback
Thread would really be overkill. It just needs to be tied to some sort of gui event like a button click
i agree
its an option tho :d
oh okay. I have one more question
nevermind, sorry I fixed it
they are probably calling opengl functions from python
someone here uses python Flet or Flutter?
Is QtQuick available for PyQt? Or do I have to stay at QtDesigner
Yes, ultimaker Cura is a good example of this
Also this is bullshit
I have a 'compiled' (pyinstaller) customtkinter interface for controlling a robot. I can tell you that it does not get cached
He's also non-specific about what is being cached but whaterver
Also, if you really were to distribute your python application commercially/prevent people stealing your code (which is easy with PyInstaller). I recommend Nuitka. Nuitka compiles python code to C and applies compile-time optimizations (its great). Because it compiles to C first and then produces a binary executable from this C code, its basically irreversible to your Python code
only works with CPython interpreter though, not PyPy etc
I've not used Cura. Will like to try
Not sure why the interpreter is needed for this considering you're not running python code
Except it's converting to bytecode and interpreting first before converting the bytecode to C, but that seems weird
it needs the cpython internals
the specifics i dont know
its just made for cpython's C API is my guess, though dont quote me on that
download any 3d printable .stl file online and download ultimaker cura
it performs well once the app actually runs, but the loading indeed takes quite long
This assumes usage of compiled langs prevents reverse engineering
If it's about compilation to native machine code, there's Cython for that
That just adds an extra layer of abstraction
- if you don't want a potential reverse engineering, just give your users web apps
Currently, I'm only concerned about the perf for Python-based gui apps
I'm still building with PyGObject so I'm yet to have a solid verdict
I was trying to install it on my windows 8 vm
Will see how that goes
- I'd prefer the Cython project to the Nuitka (still don't know what this is) project really
Nuitka seems to be transpiling before compiling.
why'd u use win 8 as a vm
? Cython and Nuitka are unrelated lol
I know they are
well yes they are to some extend
does cython also allow python to be a binary executable
It's just a vm I use for random stuff
without actually shipping the interpreter along with it
It compiles Python
basically
There's no interpreter
It doesn't use CPython
Yep. But that's not generating a binary though
and wraps this in a standalone executable
It's just an executable
no, its a binary executable that has the interpeter inside of it
just like nuitka (idk about cython)
except nuitka compiles to C and doesnt include a interpreter
binary executable === executable containing machine code
first
you dont understand what im saying
its still the interpreter thats executing and interpreting the python code
Exactly. So it's not a binary executable
It didn't generate any machine code
But it's an executable
I'm just being pedantic for sure
bro what
it is a binary executable?
a .exe = a binary executable
thats literally what a exe is
how they bundle the python interpreter in there along with your packages and python files, i dont know
but yes nuitka:
transpiles python into c
and then compiles this as if it was jsut a c program
this isn't always the case as we've seen with pyinstaller
show
I've explained before
a .exe is literally encoded binary
idk what youre saying thats literally what a .exe is
if you have any .exe ever, its a binary executable
enough 'binary executable' because this is just a pointless discussion
In the case of pyinstaller, it's NOT machine code
if you dont want your python executable to be reverse engineered, not be large in size (due to pyinstaller shipping the interpreter) and be fast, then use Nuitka
π
It's just embedded CPython and byte code
a .exe is fucking machine code what are you talking about LOL < im wrong here
Prove to me then
Not the same for pyinstaller
How is the machine code generated?
Yet you claim I'm wrong?
It's simple. Python is an interpreted language
The Pyinstaller executable still uses the interpreter
It is NOT compiled, like Cython
So while it's an executable, it's not binary in the trad sense
Na
It compiles python directly to machine code
So I think the compiled/interpreted dichotomy is just funny
Java is both compiled and interpreted
? i think this is incorrect
is this an option
because the standard is that you can compile your .py into C code
oh well whatever
imo, Nuitka is one of the good ways to create python exe's and actually make it ready for distribution
If the compilation is the problem, then Cython does same job then
i mean, nuitka already does the C to exeuctable compiling
Cython doesnt, you need a seperate thing for that. Tho it doesnt really matter
no i dont think so
i dont know cython too well but
cython does really put an emphasis on typing everything right
wouldnt be an issue for me, i type hint everything xd but still
does seem like nuitka also benefits from type hinting
static typing is optional in cython
The nuitka project is really different from Cython in that it creates standalone binary executables.
Cython doesn't do that. It just creates shared object files you can import
can you elaborate on shared object files
Those are python extension modules (.so on UNIX-like systems and .pyd on Windows)
Basically, Cython "transpiles" (not sure why they say compile) Python to C
And then the C compiler is used to generate the .so file
The file can be imported in Python/CPython code like a regular python module
Still maintaining the Python API
So with Cython, you still kinda rely on CPython
Nuitka is different
Of course, Nuitka relies on CPython too but it's embedded in the executable and which is not really interpreted
yes, and afaik QtQuick and QtDesigner aren't related in the way you imply
you can use QtQuick without QtDesigner
regardless of the stack you're using I mean
the old discussion that nuitka is better than cython, eeww
if you have constructive criticism, it would be better than random useless edgy comment
now you're critic about being kind? man, just do whatever you want
it's not really about being kind or not, it's about learning stuff. I think we're all here to learn and/or share. If you explain your point of view I could have learn something.
They have different purposes lol
Nuitka is for the sake of a (distributable) executable, cython is for the sake of transpiling and optimizing to C code and back
:incoming_envelope: :ok_hand: applied timeout to @digital rose until <t:1705585611:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
There was never a conflation on my part though
I also think comparing them is a category error
Cython doesn't completely replace CPython.
For a full app, you still need CPython, even with optimised Cython code
Doesnt cpython support cython in their own to byte code compiler
Or that done after?
I dont know cythonβs role in cpython
Cython's role ends at transpiling to C IMO
π
The C compiler is responsible for generating the shared object or dynamically linked library which the CPython code calls
To use the .so or .pyd file, you use the ctypes module I guess
For those who already know C/C++, I don't think you need Cython
You do not need ctypes for pyd
The import machinery supports it
Combined with a .pyi alongside it is how most libs are working
nuitka can be used to make code more efficient, just like mypyc or cython
id prefer cython for that tho
cython seems to do a better job at that
than nuitka
in my experience, nuitka produces faster code than mypyc and cython (if you give cython pure python code)
of course, if you write in cython lang, it will produce faster code
How is nuitka able to produce fast code w/out static typing?
how do you download a specific package to a different version of python
You can use virtual environments?
I have this code to open up a popup dialog when the button is pressed. It does that, but when I close the dialog, the program freezes for several seconds, and then the main widget closes. There is no error message. What is causing this and how do I fix it?
from PyQt6 import QtCore, QtWidgets, QtGui
from PyQt6.QtWidgets import QDialog, QMessageBox
import sys
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("window")
self.Button = QtWidgets.QPushButton("button")
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.Button)
self.Button.clicked.connect(self.ButtonClicked)
def ButtonClicked(self):
dlg = QMessageBox.critical(self,'Error','message')
dlg.exec()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.show()
sys.exit(app.exec())
is it not good practice to subclass QApplication btw? just asking
recently transitioned from tkinter to pyside/qt
Anyone good at tkinter? TL:DR I have the screen update when an event happens and doesn't really need to any other time. But sometimes a label or frame will just disappear and not come back for sever updates or if i resize the screen. Any idea how to fix this? doing a self.root.update() with or without an after only causes flickering.
QMessageBox.critical handles the exec. It returns the button that was clicked, which means you don't need dlg.exec() on the next one
That fixed it, thank you!
Does anyone know how i can rebind a scrollbar in tkinter?
i followed a tutorial which shows me how to make a scrollbar using canvas so i made one but now i want to update the contents of the frame in the canvas to contain variable amount of things but the scrollbar does not update to that
#create scrollscreen
scrollScreen = Frame(homeScreen,width=420,height=360,bg="black", bd=5)
scrollScreen.pack_propagate(False)
scrollScreen.grid(row=1, column=3, sticky='news',rowspan=10,padx=20)
#create feed canvas
feedcanvas = Canvas(scrollScreen,background='black')
feedcanvas.pack_propagate(False)
feedcanvas.pack(side=LEFT,fill=BOTH,expand=1)
#create feed
feed = Frame(feedcanvas,background='black')
#add feed to feed canvas window
feedcanvas.create_window((0,0),window=feed,anchor='nw')
def updateScrollBarFeed(event):
feedcanvas.configure(scrollregion = feedcanvas.bbox("all"))
feedscrollbar = ttk.Scrollbar(scrollScreen,orient=VERTICAL,command=feedcanvas.yview)
feedscrollbar.pack(side=RIGHT,fill=Y)
feedcanvas.configure(yscrollcommand=feedscrollbar.set)
feedcanvas.bind('<Configure>',updateScrollBarFeed)
If your screen is rebuilding or auto updating regularly, you'll need to call / create an update function. You can make it specific to the scroll screen if you want. Then when adding something new, it'll show.
So I'm fighting with tkinter and its docs. All I'm trying to do is grab the first display line in the box that I create, but it's not really working out. This is the section I was trying to understand in the docs about indices and such: https://tkdocs.com/tutorial/text.html#modifying
So at first I was trying to use that n.end: index, which should be the end of the nth line, but further down I saw something more interesting
Line numbers in indices are interpreted as logical lines, i.e., each line ends only at the "\n." With long lines and wrapping enabled, one logical line may represent multiple display lines. If you'd like to move up or down a single line on the display, you can specify this as, e.g., "1.0 + 2 display lines".
So then I try something like
mytextbox.get('1.0', '1.0 + 1 display lines")
and that... gets me the first character and nothing else? Any idea what I'm doing wrong here?
Text: Part of a Modern Tk Tutorial for Python, Tcl, Ruby, and Perl
it seems to only work correctly once the UI is actually rendering, otherwise it gives that dubious output ```py
from tkinter import Text, Tk
from tkinter.ttk import Button, Frame
app = Tk()
app.grid_rowconfigure(0, weight=1)
app.grid_columnconfigure(0, weight=1)
frame = Frame(app, padding=10)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
frame.grid(sticky="nesw")
message = ", ".join(map(str, range(100)))
text = Text(frame, width=40, height=10)
text.insert("1.0", message)
text.grid(row=0, sticky="nesw")
def callback():
print(text.count("1.0", "end", "displaylines"))
print(text.get("1.0", "1.0 + 2 display lines"))
button = Button(frame, text="Count", command=callback)
button.grid(row=1)
app.mainloop()```
Anyone good at tkinter? TL:DR I have the screen update when an event happens and doesn't really need to any other time. But sometimes a label or frame will just disappear and not come back for sever updates or if i resize the screen. Any idea how to fix this? doing a self.root.update() with or without an after only causes flickering. full code upon request if you like
Hi, i need example of easy solution how to pass data from one tkinter window to another. Anyone is able to show some code?
It depends what you mean? The window itself doesn't store the data. The code responsible for displaying the window is where the data is held
From entry to treeview, but the object is not important, more important is how to do it. Since i create new windows with variable which i declare function in another file. I need to pass data from one opened window to another.
What widget are you using for your extra windows?
Tk
Then you won't be able to. You shouldn't/can't have more than one Tk at a time
Tk is your event process and main window
if you want additional windows in a single UI program, you should be using tk.Toplevel
are you using classes in your UI?
Ill try it later at home, ill come back if there's still issue. Thanks for now
I'll share a basic toplevel example, 1 sec
import tkinter as tk
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
self.entry = tk.Entry(self)
self.entry.pack()
tk.Button(self, text='Press Me', command=self.update_popup).pack()
self.popup = tk.Toplevel(self)
self.popup_text = tk.Label(self.popup)
self.popup_text.pack()
def update_popup(self):
self.popup_text['text'] = self.entry.get()
root = MainWindow()
root.mainloop()
this creates two windows. If you type something into the main window and press the button, it updates a label in the other window
My tkinter window has an issue with displaying everything.
every time I run the window update not all frames are visable anymore. If i resize the window in any way, it all gets fixed till the next update.
Anyone know how to fix this? I'm sure it's cause I have too many frames.. not sure how to reduce that and still work the same way.
Or if anyone can look at what I'm working on and suggest a better option for the ui
is class-based tkinter the only way to go? im not used to OOP and much prefer manipulating functions and such,
is there a genuine major advantage to using class-based tkinter?
class based GUI in general is very nice. I also think GUI is a nice approachable way to actually understanding OOP and becoming more comfortable with it. Subclassing widgets to create new widgets with custom functionality is very powerful
for example I created a custom class that creates this widget. Now I can reuse this in any project going forward. Useful for image or text offsetting
what about for entire pages though
i understand subclassing to make individual widgets but
it's still very handy to be able to use attributes to manage the state of your UI more easily
but also, if you're at the point where you want to use classes for GUI, I think you're ready to move on from tkinter to something better
Feel free to paste the code here to share. You're much more likely to get help if you share your code upfront
thank you, i'll do that.
that is so weird, I thought it might've been some race condition or something? But even after using sleep(5) before calling print(text.get("1.0", "1.0 + 2 display lines")) it still only prints a single character, but I made a button like you did, and it seems to work fine. Dunno why it messes up if I just call it directly
I'm not going to want to tie it to a button... so I wonder if I can figure out what's going on. I'm basically making a very basic typing test, and one text box will be just to show the text the user needs to type. Playing with functions to see how I'll match everything in the first line, so I can delete it and add new words to the bottom as they finish the words in the first line.
I think it's too long, comes up as message text when I try to paste it. Is that acceptible?
You can use our pasting service here
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
TL:DR I'm creating an outdoor bowling scoring system.
Can't get the screen to show everything all the time, some frames go missing at full screen after and update.
Code here:
https://paste.pythondiscord.com/GIWA
Thank you very much.
hmmm yeah I see it happening on my end too, but I'm really not sure
I've never built a tkinter gui with this many widgets on screen at once
I use pyqt for larger UI
I'm bad at qt, I am trying pyside 6, but haven't used it before. I know it's using the QT, just haven't done QT in a long time.
Either way, I would really recommend separating the bowling logic from the UI logic
and I would also recommend creating subclasses for reusable UI elements like your frames
Other then better code writing, i'm still amature writer, but do you think that might or could help as well. separate the script action into small processing chunks?
And do you mean something like a main window class, game window class, action class type deal?
every frame behaves the same way, yes? It's a box that can display 3 bowl values, and a total?
or 2 values?
I don't know lawn bowling at all
with symbols and F foul.
It's 5-pin bowling but outside so the frame rules stay the same
but either way, every frame is identical information (maybe with an exception of final frame?). You can create a separate class (inherit from tk.Frame) that displays this information. Then you can create instances of this custom frame class and update the values as required
you can have another subclass for BowlersFrames or something like that
that's a bowler, and all the frames that this bowler will bowl
then another class called BowlingMain or something that holds all of the bowlers, and can contain the additional information you have at the bottom
then you can have a separate class responsible for the actual gameplay. It keeps track of who's turn it is, what they bowled, etc. Ideally it would work just the same if it was a text based CLI game
and then you can connect all the outputs of the gameplay into the GUI
it's definitely not an easy task though, at least not for something this large
My first goal in writing this was to create as few break points or points of failure as possible. My first attempt was 3 times as large. π
after this i need it to send the info back and forth between two lanes as player swap lanes based on the number of frames bowled. but will have to grab the score from the other lane and send it here.
So it's going to get bigger.
that's a big reason why subclassing will help. You can simply write methods for these subclasses that make it easy to get/set their values
like the scoring stuff will be on a "server" deal and the lane sends over the pin information then send back the results to update the display with.
I hear you and love the feed back. I appreciate it.
Is this for mock data or this going to be really used for bowling?
going to be used. My friend owns an alley and wants to promote bowling more by doing events during teh down time (summer time)
I would highly highly recommend switching to pyside then. It has way better integration with async serverside/db functions
it will also look nicer too π
But i hate learning! Mwahahaha. So I might be on the right track with that, good to know.
Just need the right teacher, haha
this is very strange indeed, even the count() method doesn't work right if set to automatically run. If I just put text.count('1.0', 'end','displaylines') after creation and inserting words into the the text box "text" I get (364,), even though there are only 10 display lines. If I once again put it in its own function and have a button call the function, I get 10 like I should π€
is it counting the lines or the characters?
now if I keep it a separate function, but have it automatically call that function without using a button, I get another number altogether, 340 lmao
it's the exact same code, just whether I'm directly calling it or putting it into a function
but it should be display lines
both get() and text() and working as I would expect when I use a button to trigger them, so I'm assuming I'm, in general, using them correctly, just something more specific to calling them maybe too soon after initializing the text box? I don't really get it.
I tried putting sleep() but a part of me wants to think that wouldn't matter, I guess the program just stops for 5 seconds, so while it seems like I gave it 5 seconds before processing the next thing, perhaps because the program is frozen for that time, it still technically is happening an instant later in terms of processing
@terse pine Can you explain what exactly you're trying to achieve? Remove the first line from a text box and add another line to the bottom?
That's the end goal, right now I'm just trying to understand how these functions work. Basically the end function is it should compare what you're typing in textbox2, with the text already in textbox1, and as you finish the first line, all the text "move up one" to reveal another line, I could also try to make it auto scroll as well, but I'm also strugglign with the see() command, and not really sure how to get it to work with "display lines"
this very second I'm trying to figure out why I can't get these functions to give me the correct values when they're not called by a button
and now weirdness I'm getting even with a button press. I decided to try and get it to print one display line at a time, it prints the correct number of total display lines (they go past the set dimensions of the box) but the for loop only returns the first display line and a bunch of blank lines π€
def gettext(self):
print(self.T2.count('1.0', 'end','displaylines')[0])
for i in range(1,self.T2.count('1.0', 'end','displaylines')[0]):
print(self.T2.get(f'{i}.0', f'{i}.0 + 1 display lines'))```
oh nevermind, I get what I did wrong with this latest function, '2.0' doesn't actually mean anything since that is "newline" separated lines, which I only have 1 line, I need to work out the logic some other way so it goes by display lines only
@terse pine Here's some small sample code that cycles the lines
from string import ascii_lowercase as letters
import random
import tkinter as tk
current_spot = 5
def cycle_line():
global current_spot
text_box.insert(tk.END, lines[current_spot] + '\n')
current_spot += 1
text_box.delete('1.0', '2.0')
lines = [letters[0:i] for i in range(1, 27)]
root = tk.Tk()
text_box = tk.Text()
text_box.pack()
tk.Button(text='Test', command=cycle_line).pack()
for line in lines[:current_spot]:
text_box.insert(tk.END, line + '\n')
root.mainloop()
it deletes line 1, and adds a new line to the end
click the Test button at the bottom to try it out
where does 27 come from?
that was just to create my example data, it's not really important for the overall logic
but 27 because range stops 1 before so I get 1-26, but I'm slicing [0:i] which also stops one before, so we're getting [0:26], which is all the letters of the alphabet
I probably could have written it nicer, but it was just to generate sample data so it wasn't important
Could I do something like this:
I'm sure I'm doing something wrong but testing for now.
class Widget(QWidget):
def __init__(self):
super().__init__()
grid_layout = QHBoxLayout()
for i in range(10):
frame_layout = QGridLayout()
foul_frame = QPushButton("1")
ball1 = QPushButton("X")
ball2 = QPushButton("/")
ball3 = QPushButton("R")
frame_score_show = QPushButton("450")
frame_score_show.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
frame_layout.setRowStretch(2, 2)
frame_layout.addWidget(foul_frame,0,0)
frame_layout.addWidget(ball1,0,1)
frame_layout.addWidget(ball2,0,2)
frame_layout.addWidget(ball3,0,3)
frame_layout.addWidget(frame_score_show,1,0,2,4)
grid_layout.addLayout(frame_layout)
self.setLayout(grid_layout)
Can you show what the expected result is?
What is the widget meant to look like?
I get this, but repeated 10 times
Yes, I think I got it but have to shrink it a bit.
class Widget(QWidget):
def __init__(self):
super().__init__()
self.num_bowlers = 3
game_layout = QVBoxLayout()
for i in range(self.num_bowlers):
bowler_layout = QHBoxLayout()
bowler_name = QPushButton("Name")
bowler_layout.addWidget(bowler_name)
for k in range(10):
frame_layout = QGridLayout()
foul_frame = QPushButton("1")
ball1 = QPushButton("X")
ball2 = QPushButton("/")
ball3 = QPushButton("R")
frame_score_show = QPushButton("450")
frame_score_show.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
frame_layout.setRowStretch(2, 2)
frame_layout.addWidget(foul_frame,0,0)
frame_layout.addWidget(ball1,0,1)
frame_layout.addWidget(ball2,0,2)
frame_layout.addWidget(ball3,0,3)
frame_layout.addWidget(frame_score_show,1,0,2,4)
bowler_layout.addLayout(frame_layout)
bowler_total = QPushButton("450")
bowler_layout.addWidget(bowler_total)
game_layout.addLayout(bowler_layout)
self.setLayout(game_layout)
This is where my amature is still showing. π
Can you show me an image of a bowling frame for 5 pin?
one sec
There's a 4th space at the top left for Indicators like crossing the foul line and such
MAX is FFF would be in there
Some alleys use dots instead but same function
ok, so 4 across the top then
yes
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class BowlingFrame(QWidget):
def __init__(self):
super().__init__()
main_layout = QVBoxLayout()
main_layout.setSpacing(0)
main_layout.setAlignment(Qt.AlignTop)
self.setLayout(main_layout)
top_row = QHBoxLayout()
top_row.setContentsMargins(0,0,0,0)
top_row.setSpacing(0)
self.foul_box = NumberBox()
self.foul_box.set_size(48, 32)
top_row.addWidget(self.foul_box)
self.num_squares = []
for i in range(3):
num_box = NumberBox()
num_box.set_size(32, 32)
self.num_squares.append(num_box)
top_row.addWidget(num_box)
main_layout.addLayout(top_row)
self.total_box = NumberBox()
self.total_box.set_size(144, 100)
main_layout.addWidget(self.total_box)
class NumberBox(QFrame):
def __init__(self):
super().__init__()
self.setLayout(QVBoxLayout())
self.setFrameStyle(QFrame.Box)
self.setLineWidth(2)
self.setFixedSize(32, 32)
self.text_label = QLabel('')
def set_number(self, text):
self.text_label.setText(text)
def set_size(self, width, height):
self.setFixedSize(width, height)
app = QApplication([])
win = BowlingFrame()
win.show()
app.exec()
ok here's an example of a single frame
just an fyi I do function before looks. but if you think it should be written different i'm all eyes.
I'm not sure how to call the right widget just yet. In tk I know how to index through it, just sure about this yet though.
but now you can instantiate the BowlingFrame 10 times to create a bowler's frames
it's very basic for now
but each of these boxes can be populated with values
this isn't super optimized either though since I just wanted to get an example up and running
first i get things to work before worring about other stuff really.
looks good. just thinking.
You don't have to write it but thinking.
So I can add a name box before, cycle it 10 times then a total box after.
PySide is differnt way of thinking for sure.
yup, exactly
if you store those 10 "BowlingFrames" in a list, and you write a method that lets you fetch the value, then that makes it very easy to get the total
loop through all your BowlingFrames, call the get_value method, store results
yall i need some help with kivy
i was following a tutorial but suddenly my code crashed for no reason
i tried reinstalling kivy and it still doesnt work
# import libraries
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
# set version
kivy.require('1.9.0')
# create a label class
class NeuralRandom(App):
def build(self):
return BoxLayout()
# load it
neuralRandom = NeuralRandom()
neuralRandom.run()
<BoxLayout>:
orientation: 'vertical'
Label:
text: "NeuralRandom"
font_size: 64
color: 0.26,0.53,0.96
Label:
text:"-"
font_size: 64
coloe: 0,0,0
Button:
text: "Generate"
font_size : 32
size: 100,50
I wouldn't call your rule BoxLayout but not sure that would cause a crash, what output do you get in the terminal?
I think I'll figure it out. Tried making 3 across but didn't go as planned. lol
runcell(0, 'C:/Users/USER/Downloads/fll app/main.py')
[WARNING] [Lang ] The file c:\users\user\downloads\fll app\neuralrandom.kv is loaded multiples times, you might have unwanted behaviors.
[INFO ] [Base ] Start application main loop
[INFO ] [Base ] Leaving application in progress...
Traceback (most recent call last):
File ~\anaconda3\Lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)
File c:\users\user\downloads\fll app\main.py:16
neuralRandom.run()
File ~\anaconda3\Lib\site-packages\kivy\app.py:956 in run
File ~\anaconda3\Lib\site-packages\kivy\base.py:576 in runTouchApp
File ~\anaconda3\Lib\site-packages\kivy\base.py:617 in stopTouchApp
File ~\anaconda3\Lib\site-packages\kivy\base.py:198 in close
File ~\anaconda3\Lib\site-packages\kivy\base.py:216 in stop
File ~\anaconda3\Lib\site-packages\kivy\input\providers\wm_pen.py:119 in stop
SetWindowLong_WndProc_wrapper(self.hwnd, self.old_windProc)
AttributeError: 'WM_PenProvider' object has no attribute 'hwnd'
it starts normal but the popup never appears and the app crashes
why not call it that?
ping me btw
Is this on a Windows tablet? @solid frigate
Calling it that is effectively adding those to every BoxLayout, you'll want to name/create your own.
That kv loaded multiple times would be something to look at too, is your main.py as shown? Or are you loading it too
whaaaat
its on a windows laptop
the first code is in main.py and the secound is in neuralrandom.kv
there is no other code parts
Thanks for your time today. One more thing.
In tk there's a hiarchy of putting things into place. Make a frame put a button ro funtion into said frame.
For PySide, is there a link to something that would explaine it better? Everything I see shows how to make each thing but nothing structured. I might be bad at google. lol
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
class Box(BoxLayout):
pass
Builder.load_string("""
<Box>:
orientation: 'vertical'
Label:
text: 'NeuralRandom'
font_size: 64
color: 0.26, 0.53, 0.96
Label:
text: "-"
font_size: 64
color: 0,0,0
Button:
text: "Generate"
font_size: 32
size: 100, 50
""")
class NeuralRandom(App):
def build(self):
return Box()
neuralRandom = NeuralRandom()
neuralRandom.run()
Does running that have the same issue?
There's one additional thing to keep track of, and that's layouts
widgets (like buttons, sliders, labels) can be added directly to other widgets/parents (and this is similar to how tkinter does place), or you can create a layout that sits inside a window or another layout. Some widgets also act as containers like a Frame would in tkinter. QWidget, QFrame, QGroupbox, and there's a few others. These can have layouts set to them
ok, I thought as much. shouldn't be to hard to figure out then.
This site is probably the best free resource you'll find
apperntly the issue is with the library
its not fit for the newer version of python i haveπ
Which version? Or is it some Spyder quirk
@solid frigate kivy's latest release was with 3.12 support so shouldn't be that
u set the version in the code
i got it 1.9
and i got latest version of phthon
ill debug it tmrw
If you were using a 1.x yea would move to a newer version -
the kivy require is a minimum check (and really of much use anymore)
its cuz its not always compatible with older phones
.rp tkinter
Here are the top 5 results:
this first link here is a good intro to tkinter
thx
Are you still working on this? I have to say, @sleek hollow is basically saying exactly what I was thinking in regard to separation of concern and writing custom tkinter widgets that are subclasses of the already available widgets, but I'll expand a little on their point. @sleek hollow Can feel free to correct me if I am wrong here on anything as I am self taught and sometimes have little things I have missed but here is my two cents.
So in tkinter, just as there is an Entry(), or a Button() widget, there could be a BowlingScoreCard() widget that has whatever abilities you give it, for example:
score_card = BowlingScoreCard(['Bruse', 'kyle' ,'Alex', 'Steve'], <anything else you need to pass>)
score_card.update(player1, next_frame, some_bowling_thing)
score_card.next_turn(....)
#Or something relevant lol I don't know much about bowling but you get the idea I'm sure.
That way your custom widget is designed to do exactly what you need for your specific purpose and you have fine control over every aspect including adding numbers/symbols to the screen at the correct players frame, updating colors (you inherit the parent widgets method so if you use Frame() for example you can do everything a Frame() object can do plus any other abilities you add. Then you simply create an instance of the BowlingScoreCard() (or whatever it actually is lol) for each game.
This also allows you to write all the logic with no coupling to the UI as the GUI just displays data how you tell it, and the logic module handles creating that data. This will make everything a million times easier for you to work with. Let me know if you want some examples.
Thank you. So cleaning up the code is great and all but the issue is the display not showing everything with each click of the button.
I'm sure that the code can be a lot cleaner though. π
I don't mean just cleaning it up, I mean refactoring it to use subclasses. That alone could solve the problem of the display becasue it prevents things from covering each other thus uninentionally hiding things. If that makes sense lol
oh, it does a little. I'm still not good at working with classes.
Yeah this is the perfect way to learn. Tkinter is meant to be used with classes in my opion. It seems complicated but it is not and it is very worth it and also sometimes just needs to be explained the right way for the specific person learning them.
For sure. I like TK. I tried learning QT today and it hurts my brain. lol
Lol yeah I prefer tk for sure.. Here I found you a quick example
Yeah, you're absolutely right about how/why you would subclass a widget. tk.Frame is great for organizing a smaller reusable collection of widgets. That being said, there's no way to be sure what's causing the frames to pop in and out of visibility without some serious refactoring and testing
which is why I still say if you're going to take the time to refactor, you might as well use that opportunity to switch to PyQt
my prob with PyQt is moving data around isn't the same and hard for me to grasp.
We can take this aside if you want to see what I've done with PySide6?
Sure. I'd say to take it slow in the beginning if you aren't already
I'm trying to put out the demo this weekend of something to look at and what not.
Just some knowledge I just don't have.
Say I build out the same screen by making a class for each frame and iterate it 10 times. How do I update the right frame info when updating the screen. I'm sure it's an easy thing, just don't know. Like do I have to point to a class[i] then the dict ect. Doesn't feel right. ect. To new at it.
Ok I need to ask a question.. is frame also a bowling term? lol
oh sorry. lol yes.
haha ok I was having a hard time figuring out what was being represented there lol
each round of turns payed by each bowler is called a frame, or bowled frame
man.. it had to be the same name as a widget lol
lol i think I names more of widgets well enough thus far. lol
although a name like frame_labels.... not exactly genius
lol naming is the worst in GUIs. How are we allowed to show code here? Can we show screen recording of GUIs or is that not allowed? Sorry i have not used discord much
back tick*3 at before and after your code if it's not too long.
You're absolutely right with this. You can store your bowling frame widgets in a list and access them with [i]
so if I created a bowling frame widget, I could write a method for adding the latest bowl
if I had a variable that kept track of the overall current frame, then I could just feed that information into my bowling frame list
this is pseudocode, but it would look something like this
self.bowling_frames[self.current_frame].bowl(5)
it could even go a step further with keeping track of the player too
So I already have them as they are in a list. When I call the class to populate so have to call the class when updating or within the class update a main frame class dict?
self.bowling_frames[self.current_bowler][self.current_frame].bowl(5)
my code already does that
I'm sure i'm not understanding working with classes in the setup part.
it depends how granular you get with your classes. I think the important bits are
A single frame of bowling (contains numbers, fouls, totals)
10 frames of bowling for a single bowler (10 instances of your bowling frames)
An entire game board (10 frames created per bowler)
You can handle all the actual gameplay value updating from the overall game board class (or you could create one more class that acts as a "manager")
not quite the same setup, but here's an example of one of my UI that I use for exporting animation data
This is defined with one class
called a Clip
this same is 4 bowlers but can be up to 12 average 6 bowlers
This is my ClipManager class. It's responsible for keeping track of how many clips I have, and it can fetch all the data from them
how much functionality do each one of these litte sub frame have? Like the are dynamically updated right?
they are
@sleek hollow you are awesome. π I bow to you and @empty aspen knowledge.
Definitely don't hardcode it to a specific number of bowlers. If it works for 2 bowlers, it should theoretically work for 100 bowlers
I'm not hard coding to any number. I import the number and names.
QScrollArea widget will be useful if there's many bowlers and you don't have space to display them all at once
That's what I use here
yea, that's a later thing as for now it'll only be 6 bowlers till I get all functions working.
I have a scroll function on the main screen that sets everything up.
you should write all your bowling logic "in a vacuum". Then it's up to the UI to know what to do with that information
like calculating a frame of bowling. You should have a function that can take in values, and calculate the score
it doesn't matter if you use a UI or not, it should take in values, and return a score
I don't know if you seen the full code or not.
then it's up to the UI to feed it the values, then take the output of that function and display it
I do have an update function
but from what you shared last time, it was very directly connected to your UI
you need to write the bowling logic separate from the UI
just take a moment to think about all bowling logic that you'll need
think about inputs and outputs
I find it really helps to write "stub" functions as little placeholders
should I move them to a separate py and import it or same but separate by class?
up to you
theoretically the bowling logic should be so airtight that you could create a separate bowling program using that same class
like if you wanted a CLI version of it
keep it as decoupled as possible
ok
how do i make python apps with interfaces
i want to make an adventure game but idk how
like ik how to make one that can be used via terminal
Thats what I was going to say. I write a class so it just creates data and then I can pass it to either a cli or a GUI and it works the same.
Does anyone here use PySimpleGui? If so does anyone have a good tutorial on how to use it with OOP?
This is what I learned tkinter with years ago.. it took me a while to undertsand this but once I did it helped a lot.. this example is a bit old and its from John Greyson's book Python and Tkinter Programming (but updated for python 3). Its just a learning script but it shows the power of what @sleek hollow and I are talking about as far as subclassing. The separation of concerns could be better but it's not the point of the example.
A lot of the power of these classes also comes from writing methods to interact with the data within that class
yes
so a bowling frame class makes sense to have methods like "bowl()" and "get_total()"
I think this is all great but I still missing the OG understanding.
Like the main screen should be the top frame and the bottom 2 frames.
Then I build a game class to put into the middle as that can change.
How do I put that into that middle frame.
Do I create a master frame in the class then, I guess add that frame into the main screen frame? or not do that?
I get classing out functions.
honestly if it were me, I would write the entire program with no GUI. Once I had a program that could produce the data I needed, I would start to create a custom widget for those little sub squares that are dynamically updated. I would write them to be ready to handle displaying the data they are passed. Then I would create a dashboard style layout with frames. I would pack the instances of my custom widget into the dashboard sections. See how I create my frames (using a custom Dashboard class I wrote), that allows me to just pack the custom Tree viewer I wrote? I wrote them completely separately, but they just plug in to each other.
It works with no gui. lol
so then can you get all the non GUI code in to a separate file?
I mean it's 25 lines but yea. It normally is as all that data comes in externally.
I only put it in this file cause the GUI was messing up.
oh the non GUI code is only 25 lines?
Not sure if you saw the code or not.
lines 320 to 523 come in as a data point conisting of 4 dict's.
Not large though.
Then line 525 to 562 is the update I have to update the gui. The gui is 300 lines.
so normally 320 - 523 are not there.
Keep in mind I have them in their own class and not each def as a class.
Ok. I did see the code and i have it open here but I looked at it from a "why are the frames jumping" perspective as I realized I don't know anything about bowling lol
lol Well if there's a bowling center any where near you, you should try it, it's fun.
There's 2 types, 5-pin and 10-pin. If I was coding 10-pin, I would be done forever ago.
lol I haven't done it since I was a kid. I started seeing things like turkey and I was like.. hmm yeah I know nothing lol
do you watch or play any sports?
I do jiu-jitsu and watch football
lol well I'll make it super simple as I can.
Each ball is a down and each frame is a qtr. (american football)
Each bowler gets up to 3 balls to knock them all down.
if all in 1 - strike
if all with 2 - spare
ball 3 is ball 3.
If you get a strike the next 2 balls count to that frame score. so gotta look back.
if spare next ball counts to that frame.
After each blower gets a turn a new frame starts.
Then add skip functions and incase someone is late or in the bathroom. Reset in case the pins don't setup correctly.
hitting throw ball buton simulates the ball crossing the ball senor and hitting or missing the pins.
I was seeing frame and not realizng that lol
data[bowler#,frame#,Ball][ball value 0,0,0][symbol 0,0,0,0] the forth is tracking if a ball is thrown as you can't skip after the first ball.
This goes into the update at the bottom and updates the ui up top.
Yes.
Trying to get more people to play bowing. So setting up lawn bowling at events and bowling at events indoors where people can just come play and find enjoyment in the game to come out the bowling centers near by.
ohh cool
So I already build the physical bowling setup to detect pin drop and return the balls. just need to get the screen to work.
there's a laptop setup to enter names and what not, send it to the lane where there's monitors of different size, doing this on the cheap.
its cool tho haha
I think the frames are resizing, if I can get them to stay in place one in place. That would be the real goal.
frame frames. lol
yes.. which is why you need a custom widget
aka don't resize once there.
so notice how the buttons on the calculator dont do that?
well I wanted to do a set size but on differn't screens it looks really messed up.
they are each containerized on their own frame
and likely group onto another frame all together
right and I thought I kind of set it up like that as it builds the name frame then the game frame then total and set weights to each in the grid setup.
yeah I see what you are saying
so I'm just not kowledgable enough for sure.
I tend to use pack() and let them expand
sometimes certain apps are design to not be resized also
So I tried packing everything. It was a mess. grid in the pack got the results so much easier for the most part. π
yeah haha you have to manage that or it will yell at you lol
well it looks great. till it fails. :S
ok so those little sub squares are "bowling_frames" and they are tracking the results of each "ball" of each turn of each player.. yeah?
Yes.
top left to track going over the foul line with a max output FFF.
then ball 1, 2, 3
oh so that is why there are 4 on top, and the one on bottom?
so one thing with the alignment to not change is that the text can't cause the parent widget (where you packed your label) to change size
ok
Not sure if you saw my message, but we can take this to a vid call if you like. Might be faster. :S
I did not. I actually have to run to pick up my daughter now, but I will look at this more when i am back
hit me up with an @ when you'd like to chat more.
same goes with @sleek hollow
for sure ttys
be safe
Does someone know a good module for prompting in python? I'm currently using InquirerPy and I love it, the only thing is that it taskes really long to detect keyboard presses while in a prompt. See some testcode below:
# import libraries
from InquirerPy import inquirer
# create basic prompt
prompt_answer = inquirer.text(
message="test", default="", mandatory=True,
)
# define function to handle escape key
@prompt_answer.register_kb("escape")
def _handle_escape(event):
print("escape pressed")
event.app.exit(result="escape pressed")
prompt_answer.execute()
InquirerPy is based on PyInquirer, but this module is a bit dated and doesn't even work on python 3.11, which in turn is based on prompt_tools. Can somebody help fixing this slow keybroard press detection or do I have to use another module instead of InquirerPy. If so, which one do you recommend?
P.S. I don't really want to a GUI, just a little bit more shiny than plaintext in the python console.
Thanks in advance
How exactly do you define "shiny", i.e. what is input() missing?
https://inquirerpy.readthedocs.io/en/latest/pages/prompts/list.html If you look at the top of this site, you can see an example of a select menu. This is something you can't do really easily with input() I thing. With this module you can also prompt a check list etc.
Right, but you are talking about text input, are you not?
@dire barn text input but also menus where you can select what you want to do
This is an example of a menu using PyInquirer
# import libraries
from InquirerPy import inquirer
from InquirerPy.base.control import Choice
import time
import keyboard
from threading import Thread
def detect_key_press():
global start_time
while not keyboard.is_pressed('escape'):
pass
start_time = time.time()
# create basic prompt
prompt_answer = inquirer.select(
message="select an action",
choices=[
Choice("add", "Add"),
Choice("remove", "Remove"),
Choice("edit", "Edit"),
Choice("print", "Print"),
Choice("settings", "Settings"),
Choice("help", "Help"),
Choice("quit", "Quit"),
],
)
# define function to handle escape key
@prompt_answer.register_kb("escape")
def _handle_escape(event):
# print how long it took to detect the escape key
global start_time
print(f"escape key detected after {time.time() - start_time} seconds")
print("escape pressed")
event.app.exit(result="escape pressed")
start_time = 0
thread = Thread(target=detect_key_press)
thread.start()
prompt_answer.execute()
Using the code above I time how long it takes to detect the escape key and on average it was like 1.5 seconds. Is there maybe a way I can use PyInquirer and threading in combination with each other? The thing is that I still want to use event.app.exit(result="escape pressed") and that it won't work without the decorator.
I did some more testing and the problem only occurs when using escape. There are maybe some other keys but I didn't find any
This is because of how special keys work in a terminal. If the library for example wants to react to arrow keys, those are given to the program as a sequence of several keys, starting with "escape". To know whether you meant to press escape, or something else follows to mean a special key, the library has to wait for a bit. But 1Β½ seconds seems excessive. Maybe this timeout is configurable?
Looks like InquirerPy uses prompt-toolkit, which has a ttimeoutlen option
so I need help using tkinter with custom tkinter, I am trying to center these grid like view, but to no avail, its impossible for me.
class Section(tk.Frame):
def __init__(self, master=None, title="", **kwargs):
super().__init__(master, bd=2, relief=tk.GROOVE, **kwargs)
self.title = title
self.info_var = tk.StringVar(value=f"{title}: No data")
title_label = tk.Label(self, text=title, font=('Helvetica', 14, 'bold'), justify='center', pady=10)
title_label.grid(row=0, column=0, columnspan=2) # Place the title label in the first row, spanning both columns
info_label = tk.Label(self, textvariable=self.info_var, justify='left', padx=10, pady=10)
info_label.grid(row=1, column=0, columnspan=2) # Place the info label in the second row, spanning both columns
# Configure rows and columns to expand and fill available space
self.grid_rowconfigure(0, weight=1)
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(1, weight=1)
def update_info(self, new_info):
self.info_var.set(new_info)
def handle_event(self):
# Add your event handling logic here
pass
class Dashboard(tk.Frame):
def __init__(self, master=None, sections=[], **kwargs):
super().__init__(master, **kwargs)
self.sections = sections
self.exit_event = threading.Event()
# Arrange sections in a 2x2 grid
for i, section in enumerate(self.sections):
row = i // 2
col = i % 2
section.grid(row=row + 2, column=col, padx=10, pady=10, sticky="nsew") # Make the sections expand and fill their cells
exit_button = tk.Button(self, text='Exit', command=self.exit)
exit_button.grid(row=4, column=0, columnspan=2, pady=10, sticky="nsew") # Make the button expand and fill its cell
# Configure rows and columns to expand and fill available space
for i in range(5):
self.grid_rowconfigure(i, weight=1)
self.grid_columnconfigure(i, weight=1)
def exit(self):
self.exit_event.set()
self.master.destroy()
class MyAppGrid(CTk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
on_duty_section = OnDutySection(self)
apparatus_section = ApparatusSection(self)
incidents_section = IncidentsSection(self)
responders_section = RespondersSection(self)
self.sections = [on_duty_section, apparatus_section, incidents_section, responders_section]
self.geometry('600x400')
dashboard = Dashboard(self, sections=[on_duty_section, apparatus_section, incidents_section, responders_section])
threading.Thread(target=self.event_loop, daemon=True).start()
def event_loop(self):
while True:
for section in self.sections:
asyncio.run_coroutine_threadsafe(self.fetch_data(section), self.event_loop)
section.handle_event() # Simulate handling section-specific events
time.sleep(1) # Simulate fetching data every second
async def fetch_data(self, section):
# Simulate fetching data asynchronously (replace with actual logic)
await asyncio.sleep(1)
new_info = f"{section.title}: Updated data at {time.strftime('%H:%M:%S')}"
section.update_info(new_info)
So I omitted some codes since I don't think they're relevant
@sleek hollow & @empty aspen I figured it out. in the label creation, width = value. it sets the number of expected charictors. This prevented the resizing to occure.
some flashing occurs but it's very minimal/
@sleek hollow & @empty aspen Still would love some help with the code cleanup ideas. π
Thank you I'm going to look it up
I found this in application.py in prompt_toolkit. Could it be that both these timeouts are added?
Anyone here knows why PySimpleGUI does not let you check a window size and position before closing it?
while True:
event, values = self.window.read()
if event == PySimpleGUI.WIN_CLOSED:
print(self.window.size)
self.save_window_config() # Store the window size to the config file
break
elif event == 'Add Note':
self.add_note()
# Close the window after saving the configuration
self.window.close()
This print never works, the error is:
My own opinion: but I obv cant answer this, since im a beginner in making UIs, i think using customtkinter is better
The way I understand it that should only be the case if you have a mapping for "escape", but also one for "escape, followed by the letter g" or something like that
Yes I think that too. Not using escape as exit key then
I've always used PySide which to be honest is a lot superior, but for the funsies of learning I tried to create an app with PySimpleGUI and I'm quite disappointed haha
Can someone help me with this thing? pip install pyside6 but the pyside6-uic is not working.
probably WIN_CLOSED is emitted when a window gets closed, at which point it's too late to request its size and stuff.
that's my guess, so I've checked in the documentation and there is a flag to enable events on attempted closing of the windows, which triggers the saving but now it do not close the window as it overrides the closing, we have to implement our own closing. What a mess for a "simple" library hahaha
@sleek hollow & @empty aspen
So I tried making them classes and now I've got a new list of visual issues. π Mostly a sizing issue:
Anyone else can see what I'm missing:
https://paste.pythondiscord.com/QEJA
Got this:
Should be this:
I've also made a few changes to my test code for the og display function here:
https://paste.pythondiscord.com/KQIA
I ended up doing the same program twitce, with pysimpleguy and with pyside6, all it took has been around 5 hours. But I am going to stick with the pyside6 version, it's a lot more stable and with less weird errors. In case anyone wonders how both frameworks adapt to a dynamic layout, both files are in: https://paste.pythondiscord.com/TPTA
I am sure it can be improved a lot, after all I am just experimenting and having fun with it.
Hi ! did anyone have some competences with PyQt5 ?
Not a good one. π
I just have a layout with one column and I have no idea how I can put two columns next to each other π
It's like this for the moment I want to double the number of column but I can't do it lol
Would you like to take a look at my code?
something like this?
more like that
I am going to assume you are using a QtWidgets.QVBoxLayout for that one? you would have to use a Grid Layout
not sure I understand what's the issue then
if you are using a grid, adding a new column is trivial
yes I know it's easy but I just can't find the trick π€£
the tricky part comes if you allow the window to be resizable and adapt the content to the new size of the window xd
Well, layout.addWidget(widget/button/element/whatever, row, col, 1, 1)
that's how you control in which column you set the element up
So I don't need this ?
self.right_column_layout.addLayout(self.fuel_row) self.right_column_layout.addLayout(self.tyre_row) self.right_column_layout.addLayout(self.first_row) self.right_column_layout.addLayout(self.second_row) self.right_column_layout.addLayout(self.third_row)
When you add elements you can specify "where"
instead of just adding and defaulting to "next one", which seems to be what you are doing
controlling the position of the row and column will give you more control
albeit a bit more complex
wait and see how it all turns out and make fun of me knowingly π
well... if it works it works, but you should read https://doc.qt.io/qt-6/qgridlayout.html
The QGridLayout class lays out widgets in a grid.
thx
because as I was guessing, you are using a QVBoxLayout, it's there in your 5th line haha
I've always struggled with dynamic sizing in tkinter π¦
yea but if they are not in classes it's fine. π
also avoid multi-variables like this
you should use a dict or list to represent this
sure but I see that more as a code cleanup later then anything, as it's handy when finding errors upfront. For me anyway
if anything, more variables is harder to debug
Not for this brain. If ball1 doesn't update I can locate the issue quickly. :S
I can show you an example of how I would structure it in pyqt
But I do understand what you mean
from PyQt5 import QtWidgets
class BowlFrame(QtWidgets.QFrame):
SIZE = 128, 128
def __init__(self):
super().__init__()
self.setFrameStyle(QtWidgets.QFrame.Box)
self.setFixedSize(*BowlFrame.SIZE)
class BowlerFrames(QtWidgets.QFrame):
NUM_FRAMES = 10
def __init__(self, bowler_name='Unknown'):
super().__init__()
self.setFrameStyle(QtWidgets.QFrame.Box)
main_layout = QtWidgets.QHBoxLayout()
self.setLayout(main_layout)
self.bowler_name = bowler_name
self.bowler_lbl = QtWidgets.QLabel(bowler_name)
main_layout.addWidget(self.bowler_lbl)
self.frames = []
for i in range(BowlerFrames.NUM_FRAMES):
frame = BowlFrame()
self.frames.append(frame)
main_layout.addWidget(frame)
class LaneWindow(QtWidgets.QDialog):
def __init__(self):
super().__init__()
self.main_layout = QtWidgets.QVBoxLayout(self)
self.bowler_frames = []
for bowler in ['Timmy', 'Alex', 'Sally']:
bowler_frame = BowlerFrames(bowler)
self.bowler_frames.append(bowler_frame)
self.main_layout.addWidget(bowler_frame)
app = QtWidgets.QApplication([])
win = LaneWindow()
win.show()
app.exec()
it's missing the internal widgets, but the structure is here
once this structure is in place, it's now simpler to go in and simply edit the internal widgets. If I modify the BowlingFrame class, I know the placement of this widget is going to stay the same
I often will lay out my UI like this as a first pass "sketch", and then go fill things in
QFrame with Box style is a great way to visualize your widgets (since otherwise everything is "invisible" and it can be hard to see exactly what you're doing)
some more modifications. Now each frame is capable of displaying 3 bowls, and room for a total
(need 4 across the top.
the actually functionality isn't implemented, but that's ok, we're just making sure it's capable of displaying the values
ahh right
but I get you
but yes, I'm using a loop, I can just change the loop from 3 to 4
instead of adding a new variable
easy change
Seems easier then my brain computing it.
Want to see what i got going on so far?
can do a screen share meeting thing if you like.
if it's anything like your tkinter code, part of the issue is you're still cramming too much into a single class
you need to compartmentalize/encapsulate
my GUI doesn't care where the data is coming from
it just needs to know "set this label to this value"
So I have a lane entry class for reasons then a main screen class then starting the bowling game it's self in
is lane entry what happens before the game starts?
yes cause there's differnt bowling game types that can populate the main display region. For not, just getting the base working before adding other types
So It should always show this if no game is one, but changed to blue.
Then a call from the server with game type, bowler names and stats like averages and what not will be sent over to provide the data needed to start a game
In my example, I'm using the LaneWindow class to display the information during a game of bowling. I would have another class eventually that would hold that class and has all the additional information surrounding it
you can use a "QStackedLayout" to hold multiple "screens" if you want to choose what to bring forward and display to the user
you could have a welcome screen/login screen/enter names screen or whatever other "screens" you want to come up with
well all that last part gets sent, don't need a keyboard (physical or on screen) at the lanes. Just receive the data and populate
how do the names get entered? During like a registration with the front desk?
You bet
ahh ok, nice
when the lane system starts I need to know the lane before connecting to the reg desk:
yeah, that would be a perfect use of a QStackedLayout then
Once start is hit, generate the blank lane screen to wait till a game is sent
again can call and teach, less typing. lol
If you use QMainWindow, it also has a "centralWidget"
ok
so instead of QStackedLayout, you can use QStackedWidget as your main widget
and then swap in the widget you want to display
would it be better to load the main screen, popup the lane entry as it only needs to be done once, then the result back to a vaiable in the main to start the call to the reg desk that it's ready?
yeah that would be fine, you could destroy that widget once you've retrieved its value
that would be a perfect use for a signal
do I do something like:
Main_Screen.lane_id = lane_id
from the lane select. Not sure how how to send it over. The class construction for QT is a little different and I think it confuses me.
There's a single piece of info I'm missing in my brain to connect all the dots. Like a mini gap
I can show you a basic example of that but then I have to get going
appreciated
Please don't do too much.
this is the gap I'm missing. Obviously the arrow is where I'm failing
def start_main(self):
lane_number = self.lane_number_entry.text()
# Main_Screen 'variable :lane_id' = lane_number <---
self.destroy()
# Put window code here
class Main_Screen(QWidget, Ui_Main_Lane_Screen):
def __init__(self, lane_id):
super().__init__()
self.setupUi(self)
self.lane_id = lane_id
self.lane_check = False
if self.lane_check == False:
print(self.lane_check)
Lane_Select().show()
self.lane_check = True
print(self.lane_id)
alright try running just this
you do too much, I owe you a drink
it will start with just this entry. I wasn't going to build a whole num pad, haha. Type in a lane number here
Then it will display your bowler names with the current lane number at the top
It's good practice for me as well π
There's definitely still some missing connections like setting up the correct bowler names, and all the helpful methods for setting values in the frames, but hopefully this gives you a better idea of how to pass data around
Thank you again.
Np! Is there anything there you're unsure of?
Just looking at it now.
Yeah me too
Just to understand.
You set the variable to send:
lane_selected = QtCore.Signal(int) (changed for pyside6)
You emited the signal:
self.lane_selected.emit(lane)
This caught the signal:
self.lane_screen = LaneScreen()
self.lane_select = LaneSelect()
self.setCentralWidget(self.lane_select)
self.lane_select.lane_selected.connect(self.on_lane_selected)
So it looked into the lane_select that is equal to the class,
looked at the vairable signal lane_selected
and connected it to def of on_lane to action the data received.
If I'm understanding you.
yup, signals is how data gets passed around in your GUI. It's like using command=... on a tkinter button
in pyqt, most widgets have pre-built signals, like clicked for a button
command is so much easier for me.
But that helps a lot. I know it functioned kind of the same but how it actions is different for sure.
but here, I created a custom signal for the lane select widget, which gets emitted when a lane is selected
self.some_button.clicked.connect(self.some_method) would be the setup for a button in pyqt
I like this cause when I send data over, I can parse it into different variables to be grabbed but the update func.
command is nice in tkinter since you can assign a command to it in the same line that you create the button
yea I got buttons pretty good.
in pyqt, things tend to be very verbose.You need a lot more lines, even to do seemingly simple things
but that also means you have far more control over every little thing
yea same line simple functions is like wearing socks in boots, feels good.
in tkinter, you can only have a single command tied to a button though
ha ha well they both have their advanages like you mentions before.
in pyqt, I could connect the button to many different methods
signals are a good way for the main window to know when certain things have happened in the ui
for sure.
here, the main window is waiting to receive the "lane_changed" signal to know when it is meant to display the next screen
in tk you can do an active variable to act that way as well. But I knind of don't like them as you always need a tick happening in that frame. Get's flashy if too much is happening on the screen
yea, I don't really use it myself. I never saw a problem with just updating the text in a label when I need it. More control then sending a signal all around.
a good example of where you might want to set up a signal would be the total score for a frame
your actual Bowling class would be responsible for updating each bowl, but you could emit a signal every time a bowl occurs to update the total score for that frame
you could emit a signal every time a frame ends, so it knows to move onto the next bowler
it's really nice to just emit signals when certain things occur, and then it's up to you to connect up your UI to determine what widgets care about the data that was just emitted
Just opened a box of more questions. lol
I can incorporate it into my existing code and get it to work, that's great. π
Take the code I gave you and just play around with it for a bit. Try and change some values, see what happens. Use it as a sandbox for testing stuff until you really feel like you have the hang of things
then you can focus on trying to combine it or integrate it with your other code
Oh I am. Peicing it to gether to functions as I want.
Gotta add a few more things to it, that'll help understand as well.
Weekend project using PySide6. It can be improved a lot, but for 6 hours or so, I am happy.
https://github.com/Aens/Unmemorize/tree/master
I appreciate feedback. (Eventually I will use a database instead of txt files π€£ don't worry, this was just for funsies)
okay, I've gotten the grid like system which is perfect, however I need help now to expand these boxes so each box covers a side of the window:
ex.
class RespondersSection(CTkFrame):
def __init__(self,master):
super().__init__(master)
self.master = master
self.grid_columnconfigure(0, weight=1)
self.title = "Responders"
#self.pack(pady=20,padx=20)
self.grid(row=1, column=1, padx=20, pady=(10,10))
self.width = 100
self.height = 100
#self.anchor(customtkinter.S)
class IncidentsSection(CTkFrame):
def __init__(self,master):
super().__init__(master)
self.master = master
self.grid_columnconfigure(0, weight=1)
self.title = "Incidents/Calls"
#self.pack(pady=20,padx=20)
self.grid(row=0, column=1, padx=20, pady=(10,10))
self.width = 100
self.height = 100
#self.anchor(customtkinter.S)
What can I do to ezpand this?
app:
class App(CTk):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.title("FD Dashboard")
self.geometry("600x400")
OnDutySection(self)
ApparatusSection(self)
RespondersSection(self)
IncidentsSection(self)
self.anchor(customtkinter.CENTER)
if __name__ == "__main__":
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")
app = App()
app.mainloop()
cause that are custom size, you are limiting them to what you can do with them. try adding to the grid
sticky = 'nsew'
But top right being NE and bottom left being SW... ect
guys i am trying to install tkdesigner but i keep running into issues with pillow
i have tried using pip install tkdesigner Pillow==10.2.0 which gets the job done but gives this module error with urllib3. i have tried uninstalling and installing urllib3 but that didnt fix it either
yea, I never got around that either.
Either see if a version <2 of urllib3 works with 3.12 or use python 3.11 until tk designer updates to support v2.x
i used python 3.11 as well
gave the same issue
that pillow 8.4.0 doesn't support 3.11
and installing a lowe version of urllib3 didnt fix the issue either
it gave that urllib3.packages.isx.moves module not found error like on this screenshot i mentioned
i just downgraded to python 3.10 and that seemed to fix the issue for now
Had presumed the sticking point was more urllib3 (with a presumption that <2 wouldn't be supported on 3.12).
If the designer is also reliant/pinned on an older pillow (<9.2.0 perhaps) then yea will need to stick to a supported python and await updates
okay
trying to do the command of "Status Bar" to toggle the status bar on the bottom like in notepad but when the frame.grid_remove() is called in else condition it didnt work
it worked when doing it manually without the toggle
initial call
after the command is pressed
class Menus:
def __init__(self, window, textarea) -> None:
self.status_bar_toggle = True
self.status_bar()
def status_bar(self):
frame = Frame(master=self.window, height=24)
Label(master=frame, width=24).grid(row=1, column=0)
Label(master=frame, text="Ln 1, Col 1", relief=GROOVE, justify=LEFT, anchor=W).grid(row=1, column=1, ipadx=40)
Label(master=frame, text="100%", justify=LEFT, anchor=W).grid(row=1, column=2, ipadx=5)
Label(master=frame, text="Windows (CRLF)", relief=GROOVE, justify=LEFT, anchor=W).grid(row=1, column=3, ipadx=10)
Label(master=frame, text="UTF-8", justify=LEFT, anchor=W).grid(row=1, column=4, ipadx=30)
if self.status_bar_toggle:
self.textarea.insert("1.0", f"status bar toggle set to {self.status_bar_toggle}\n")
frame.grid(row=1, column=0, sticky=E)
self.status_bar_toggle = False
else:
self.textarea.insert("1.0", f"status bar toggle set to {self.status_bar_toggle}\n")
frame.grid_remove()
self.status_bar_toggle = True
the class was called in my other file
It seems excessive to recreate the status bar every time you need to display it. Create it once and store it in an attribute, then use a toggle to show/hide it
will do, thank you
what package do I use for UI
You have a few different options. tkinter comes with python already installed so it's a good place for a beginner to jump right in. If you want something more advanced, you can use PyQt
does tkinter come with some restrictions to what I can do?
do you have a specific UI in mind you're trying to make?
not really but I think I would like to start by making like a basic inventory
like a minecraft inventory for example
If you want something with drag/drop support, I'm actually not sure how well tkinter would handle something like that. PyQt has great drag/drop support though. How experienced are you with python already?
eh I honestly dont know where I would put myself ig i'd go with beginner
I know control flow and feel like I have a decent grasp on the basics
have you done any OOP/class coding?
dont think so
I'd start with tkinter then and just focus on a basic UI. Even with experience in pyqt, drag and drop can be a bit tricky to wrap your head around
alright ty I appreciate the help
I do a lot of SQL for work, and I overclock Excel for dumb things coworkers request quick one-and-done projects, but I think I would like to start developing Python scripts that can 1) collect data on a webapp so I don't have to use MS infrastructure to collect data for our various business processes, and 2) quickly work up data with some basic visualizations (think bar graphs) dumped from a SQL query into a csv. Currently use Azure Data Studio for our SQL stuff because it's free, and we use an Azure SQL db for our data storage (cheap, and our datasets are relatively small).
I've dipped a toe into both PyCharm and VSCode, but honestly they just feel clunky to me. I got my start coding back in Visual Basic back when I was in elementary school...so I'm drawn to a more minimal workspace. Anyone have experience with something like neovim? I like how stripped down it is, but I don't want to put up a big customization barrier between me and getting a few quick projects done.
Thoughts on neovim vs Pycharm/VScode for someone who does primarily fullstack data stuff?
helix is like neovim with a few better design desicions imo and more built in, ive had it for 1.5 yrs and my config is still like 10 lines of toml. A lot more stable for me than neovim distros
if you need plugins regarding sql, then plugin support is not yet merged
plugins aren't really a big deal for me. If I really need the autocomplete functionality I do my query writing in ADS anyway. Sounds like you'd confirm that a more stripped down editor as an IDE is perfectly viable though. Does helix allow Git integration? I'm currently using Github for company-accessible code like SQL queries used outside my office, etc.
yes that was my concern going in but since it supports major protocols like language servers and treesitter it doesnt feel stripped down, it is pretty similar in features to vscode, just with a tui and it is compiled rust not electron. The git integration in helix right now is pretty minimal like showing changes made to a file since last commit in the gutter.
in my mind, it fits quite well in a tui ecosystem so git could be handled by something like lazygit
How does this ui design look for an installer and auto updater I made for fun? Made with PYQT5
I am genuinly surprised that something this beautiful is possible with pyqt. in any case, a UI thing you should perhaps do is that the highlighted option should have brighter text to, well, highlight it
The title UPDATE / INSTALL has slightly more padding than the subtitle. You don't need to make subtitle all caps (it looks kinda cringe when everything is all caps), plus you are already using a slightly gray color (experiment with font weight too) anyways. Desktop shortcut can be a checkbox instead and it will still look good. Btw where is the close / minimize button?
Qt QML is very HTML / CSS like
someone knows if and how is it possible with default libraries to draw on screen without any windows? Best if cross-platform (yeah, heard of windows tools but what about linux, mac, bsd and others?)
In general, good UI design is up to the user, not the library
"with default libraries" is quite a massive constraint, here.
this supposedly-crossplatform tkinter example works for me on linux: https://stackoverflow.com/a/68443540
Tk have problem with possibility to clickthrough...
And i have no fear of embedding c/c++ inside python (as long as it won't require additional installations of anything)
libadwaita kinda gives you that look out the box
Like i'd like to achieve sort of overlay of a custom WM
To loop over pixel 2d array, get or set colors and manually detect clicks (or clickthrough or ignore)
sry to anyone who finds this horifying, but the close and minimize buttons had to be traded in to allow for rounded windows. Also I am aware of the padding issue, they both have the same padding in code, making that hard to fix.
If its not a padding issue maybe its a margin issue. Dunno if QML follows the CSS box model
yea, but there is none of either
im just gonna role with it as is, might change it in the future
It might have margin by default
Anyone around? Trying to get a class to update from another class without creating a circle loop.
do you have an example?
I figured it out. Sometimes not enough coffee or too much makes the simple things forgettable. lol
no, i set it, so I mean that there was no discrepancy between the two, as they are set to the same amount LOL
Hello, does anyone know any good solution for a realtime tui?
:incoming_envelope: :ok_hand: applied timeout to @gaunt rampart until <t:1707085210:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
lol
I camel cased the variable call.... blah. I write too many e-mails at work. Some shift habits are hard to break. Ah hahaha
I was blind to it for hours.
how to add a ba ckground image to my tkinter ui?
Do you want to fill a whole screen behind some wigets?
https://github.com/Fnerz/Tkinter-Window-Loader
ive made this mini dynamic tkinter framework. what are youre thoughts about this? is this something i should continue working on?
Hi people. I am working on little project.... I want to make .bat script to python and add gui... I already made .bat script (in attachment) and want to make GUI using tkinter... I have some knowledge of python, how tough can It be?
Looks like a fairly simple GUI. Shouldn't be too hard to make after some basic tkinter tutorials
I have a scrollable canvas with frame window placed on it. Instead of using scrollbar i am using mousewheel directly and manually updating the yview_scroll of canvas. The problem is that when canvas gets scrolled the frame (inside canvas) do not properly gets scrolled and bottom contents are still hidden.
I can't understand that what is missing to fix this issue.
Here is what i mean:
Left is before scroll and right is after scroll.
(canvas is colored red and frame inside canvas is colored yellow)
This is the updation code: https://paste.pythondiscord.com/OOYA
def _configure_frame(self, _: Any):
"""self.frame.bind("<Configure>", self._configure_frame)"""
w, h = self.frame.winfo_reqwidth(), self.frame.winfo_reqheight()
self._canvas.config(scrollregion=(0, 0, w, h))
self._canvas.config(width=w)
self._canvas.config(width=h)
def _configure_canvas(self, _: Any):
"""self._canvas.bind("<Configure>", self._configure_canvas)"""
self._canvas.itemconfigure(self.frame_id, width=self._canvas.winfo_width())
self._canvas.itemconfigure(self.frame_id, height=self._canvas.winfo_height())
def _on_scroll(self, e):
"""self._canvas.bind("<MouseWheel>", self._on_scroll)"""
self._canvas.yview_scroll(-(e.delta // 120), "units")
i want to make a simple spinning wheel, like wheel of names, with probability control and custom colours, itβs possible to make it in python or it is not the best language to create this kind of stuff
and also what is the best module i can use?
best I can't tell you as I only know Qt but it's doable, although it's quite painfull
there's no such component existing so you need to create your own, and you need to draw it yourself
oh crab
I wouldn't recommend Qt beginners to try to do this as a first project with Qt
Spinning a widget in pyqt sounds paintful
you don't have to actually spin it, only it's representation
property animation?
actually that's a good question
that's not the road I would have take instinctively
I don't think there's any sort of rotation property...
convert widget to pixmap with grab, rotate the pixmap?
you can make a fixed widget and draw it diffrently depending on some state
that's what I would have done
so litteraly drawing everything yourself
and drawing the rotation yourself
so it would not actually be rotation, it would just be the drawing of it
but like
rotation stuff, acceleration, decceleration, etc
so everything from a paintevent?
if my boss ask me to create something like this I would actively try to avoid it lol
animation might be a good idea too it needs to be investiguate
the main problem I see is like, when spinning you want to know where you ended up
I've only ever used minor property animations like colour or position
by drawing all yourself, you know that without extra work
I think as long as you know each segment size, and you know how much it rotated, you should be able to work out where it landed
oh yeah?
you can generate a pie, or use an already existing pie from assets
and rotation an image in paintevent is painless
still have to handle acceleration and deceleration
yeah, I thought using a pixmap and rotating it was the best way
generating the pixmap itself if you want something dynamic might be annoying but maybe QtChart already have something that can do that
still, wouldn't want to do it lol, i'm too lazy
yeah I think you're right that the chart is the best way to go about keeping it dynamic
so python is not the best
Qt is a C++ framework with a binding in Python
also how did I just learn that QLabel inherits QFrame....?
so much time wasted putting a label into a separate frame to style it
doesn't matter the language for your task, only the UI framework you'll use matters
ahah
the quicker would probably be to look into html/js/css
because there's probably something ready out of the box written by someone else
pygame might have something
but it probably means all your UI would need to be in the web stack
https://doc.qt.io/qt-6/qml-qtquick-rotation.html#details
^ might work too
Provides a way to rotate an Item.
anyway
Do you generally use qproperty animations at all?
To make things a bit more fluid feeling?
iβm not in web developing
β¦
idk where to start if i need to code it in css
honnestly I don't really have the opportunity
I just started QML, as in I've been working with it for the last 3 months
and usually I work on industrial apps that's doesn't need a lot of polish
Ahh fair enough
I haven't done a lot with it either, but recently started using animated background colour properties to indicate certain widgets
if they're missing information, or I want to draw attention
I'm still not sure if I enjoy QML or not
Haha what are the pitfalls?
I feel like it solves some problems while creating others
I'm not sure, I'll get back to you aabout that in a few months
it's difficult to know if the difficulty I have is because I'm a noob with it or because it's a real flaw
I need more experience with it
Hi
is it possible to create a spinning wheel (like the wheel of names) with customtkinter?
The only thing I can think of is to create a animation or gif of a spinning wheel that takes a set time, do a random num between 100-200 and run the animation that % of time and figure out where it should land at.
Can be done in any framework that lets you draw a canvas (I've made one in kivy) - but as noted you'd need to math it out
:incoming_envelope: :ok_hand: applied timeout to @trim goblet until <t:1707738017:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Anyone know how to fast learn QT?
Any ideas
I need it for a bunch of projects
With data science
practice practice practice
Yeah I know but do you think learning by documentation is great?
do some tutorials to understand overall how it works, and then you can dig deeper into the documentation to learn new widgets
Once you get the process of creating a widget, adding it to a layout, and then manipulating that widget with method calls/signals/slots, you can apply that same idea to any widget
Did you ever check out udmey.com ? They are quite good for getting up to speed with a big framework.
:incoming_envelope: :ok_hand: applied timeout to @verbal vault until <t:1707833263:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:incoming_envelope: :ok_hand: applied timeout to @late parcel until <t:1707833296:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
yeah I have a few courses on Udemy
but I am waiting for sales
any good resources for learning tkinter
.rp tkinter
Here are the top 5 results:
first link here is great
thanks @sleek hollow
ive only worked with tkinter a little bit but i found https://tkdocs.com/tutorial/index.html to be quite useful for learning its fundamentals, plus you'll find the modern themed widgets showcased there too
Modern Tk Tutorial for Python, Tcl, Ruby, and Perl
What to enter so that numpy performs the function of the numpy module.enter here(keyboard.press('shift'))
I am currently learning flet. Is there. any sort of event that is similar to "Mouse leave event"? for me, this is useful when a mouse is hovering over an animatable widget but instantly clicks off (where the wiget goes back to its initial state)
any user friendly gui type things or is it always going to be this
:incoming_envelope: :ok_hand: applied timeout to @vivid granite until <t:1707995342:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:incoming_envelope: :ok_hand: applied timeout to @true turret until <t:1707996419:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:incoming_envelope: :ok_hand: applied timeout to @digital rose until <t:1707999198:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:incoming_envelope: :ok_hand: applied timeout to @naive nebula until <t:1708001374:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
hello guys i really need your help since any fix on the internet i found is outdated. So i made this simple app and i'd like to make it possible for other people to download it and run it from their computers. I've made it an .exe file with pyinstaller but any time i bring it to desktop windows antivirus activates, deletes the file and proudly announces it to me. There must be another way to do this and if you know it please help me, also i am not sure which chat i should have posted this in so sorry. Thanks
nuitka?
Pyinstaller is marked as a virus by most antiviruses
Are there are good python gui libraries that don't have the licensing weirdness of Qt?
I mean, I don't plan on making xommerxial software woth it anyway I guess. Just feels weird
I'll give it a chance based on your word
Most tkinter interfaces I've seen look like windows 95 tbh but maybe I'm wrong
there is modern option
turns out you can download themes or something
styles
but it is very possible to build nice looking interfaces with tkinter
Kay, I'll give it a shot
I intend to make a fightcade-clone, I'm not sure that'd be possible in Tkinter unfortunately. I don't mind sucking it up and using Qt. Is something like this even possible in Qt
gtk is gpl which allows sale but you must provide source code, it also looks nice: https://youtu.be/O1Na7HBSIAI?feature=shared&t=159
it has windows and macos support but the main target is linux
it is used by gimp and inkscape although they use old versions
Collector is a GTK4/Python app that let us to easily move multiple files from multiple location in a single window. it's heavily inspired by macOS Dropover; on video is Collector v 1.0.0
Collector on Flathub
https://flathub.org/apps/it.mijorus.collector
Collector (GTK/Python)
https://github.com/mijorus/collector
Drop it (GTK/C)
https://git...
Thanks! I'll check it out
question regarding an application that i am making
if i have a app booter and i want to add a software updater to this, how hard is this to achieve? If i have a version api and download server (which im developing rn), can i just overwrite certain .py files and thats it?
its just about the general concept of an updater
the question is more about the part of overwriting files rather than the download client + server, ive already researched that
that's a good question; I'd like to hear a good answer to it too :p
my first thought is "just overwriting python files is a bad idea; what if you need to remove some old files, too?". perhaps replace the directory with the new version, instead.
mmm, i like both approaches
though replacing the whole directory may involve a way higher download size
but yea, what if you need to add completely new folders? What if you need to remove assets etc
what if you need to move files & data to another folder
im sure it wouldnt be too hard to create. I am mostly wondering what the best practices are
If something like this (open sourced) doesnt exist for python applications yet ill consider open sourcing my own system that ill create for it
looking at how one of the tools I know autoupdates does it, it seems the answer is innosetup - all of its releases are packaged with it, and when needed it downloads the latest release's installer from github and launches it.
https://paste.pythondiscord.com/UVBQ anyone able to help with the error here?
:incoming_envelope: :ok_hand: applied timeout to @digital rose until <t:1708194430:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Compiling and distributing gtk binaries on windows is a nightmare. Its not really cross platform tbh, I have quite some experience with it
yeah wanted to include the linux focus caveat
i havent done it but would look at gimp or inkscape, i believe it involves msys and static libs
maybe with winget it could be more like the experience had with apt, dnf or guix
a shame because they made the renderer backends and everything
I have this omg.jpg file in a folder called images
app_folder
|-images
| |- omg.jpg
|
|- main.py
and this is my simple code:
from tkinter import *
window = Tk()
window.geometry("600x600")
window.title("Skibidi Clicker π")
icon = PhotoImage(file="images/omg.png")
window.mainloop()
when i run it, i get an error:
couldn't open "images/omg.png": no such file or directory
what am i doing wrong?
Did you try ./images/omg.png
hmm does it even make a difference?
its better to give full file path anyway, like C:\Users\username etc
that's a bad idea too - now your project breaks if you ever move it or upload it to github or whatever.
ok you can do it relative to the current file using __file__, or better for restructuring is to have some function that gets the projects path in some file at a constant location, and then paths are found relative to that
pathlib is good too
eg some file at constant location:
def getProjectPath():
return pathlib.Path( __file__).parent
or even setting some global as it will likely remain constant during execution
then elsewhere:
icon= PhotoImage(
file= getProjectPath()/ "images/omg.png",
)
pathlib is object oriented path handling and works with any function that accepts a pathlike, if not it can be cast to a string
pep8 can sugmanuts
:ok_hand: applied timeout to @livid badge until <t:1708269548:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Anything like Blazor in Python? Or anything that would allow you to build apps in a html-esque language? Idk
Been looking into pywebview but that requires Javascript I believe
perhaps the web assembly stuff could be of use ik there is some crossover with python
i think with web assembly one is still pushing content to the html backend layout thingy
ig gl area stuff exists
https://pyodide.org/en/stable/ this is cpython compiled to a wasm target, not some physical architechture like x86
so it can be run in the wasm browser ( virtual machine i believe) like that implemented in firefox
i mean there is stuff like relm too which is said to be declarative, relm specifically is rust tho
also the immediate mode stuff where the ui is completely generated each time step instead of incrementally but these are slower than incremental, especially with python probs
also both gtk and qt have markup languages
( builder xml or blueprint) or ( qml) respectively
but then you miss out on the dynamic construction of ui that a general programing lang gives you
Good point, ah well. Guess I'll just keep learning Qt
I'd rather just use python itself. Seems expressive enough
!pypi ttkbootstrap
close ig from styling perspective
import reflex as rx
class State(rx.State):
count: int = 0
def increment(self):
self.count += 1
def decrement(self):
self.count -= 1
def index():
return rx.hstack(
rx.button(
"Decrement",
color_scheme="ruby",
on_click=State.decrement,
),
rx.heading(State.count, font_size="2em"),
rx.button(
"Increment",
color_scheme="grass",
on_click=State.increment,
),
spacing="4",
)
app = rx.App()
app.add_page(index)
saw offered reflex
haven't tried personally
Personally driving towards the field of using templ + applying htmx. looks like really strong backend friendly combo.
templ gives me nice html/css templating with type safety and programming language usage.
htmx replaces me need to use javascript, it is rather rich in what it offers. Give a check for its overview here
Interesting, thanks for the note
what is the best gui module for python
depends on your needs really
ok
What are you trying to do with gui?
Like calculator modern one and snake game after it
How new are you to python?
Like started 2 minutes ago
Oh
I mean 2 months ago π
Ahh, haha
I'd recommend tkinter as a starting point. It's not the best gui, but it's fairly beginner friendly
.rp tkinter
Here are the top 5 results:
Ok
Hello Everyone, I am a fairly new developer and I am looking for some guidance into picking a proper library / framework to use to build the app User interface
I am looking to build a modern user interface for a simple app for a medical xray device. This app reads the height and distance of the xray machine from the patient, using U-art protocol from sensors and displays it on the screen. It also sends motor signals to move the machine up and down, left and right using GPIO.
This app runs on a raspberry pi 4B
I am having a hard time determining which library to use to build the user interface. This user interface is simple but it does have a background image with Distance and height shown as text in a transparent card.
It also has a settings drop down for a configuration and calibration options which the user can interact with and set
What do you guys recommend? Any help would be greatly appreciated!
whats the goal of having a venv honestly?
i thought by creating venv i could run the code in any pc i wanted.
since ur on linux, id recommend gtk, i wouldnt recommend it: if you need to use vulkan to draw ,if you need to embed x windows within the ui, if u need easy windows or macos support
https://canary.discord.com/channels/267624335836053506/1210028845307269190 @elfin basin if you're interested in how classes can be used with tkinter, here's something ive written up that loosely mimics your program, but with each frame getting its own class and data being passed around in parameters instead of global variables:
https://gist.github.com/thegamecracks/e16421a8f49a071643ddd33c8d6832b7
What do y'all think about this gui
Functions in functions are cute
ok
made infinite craft with the help of local LLM and pyside6 for GUI
I'm using babel to translate my interface to various languages. I was wondering if I should make a english.po file since all strings are in English so there's no need to create that file because it'll fallback to the english str in the app code
Awesome to see it
:incoming_envelope: :ok_hand: applied timeout to @digital rose until <t:1708780537:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
in flet how do i change the size of a FilledButton? i have tried wrapping the content in a container and changing its width but that didnt work
:incoming_envelope: :ok_hand: applied timeout to @candid sedge until <t:1708814631:f> (10 minutes) (reason: duplicates spam - sent 5 duplicate messages).
The <@&831776746206265384> have been alerted for review.
class MyApp(App):
def hex_view(self,filename: str | Path) -> FloatLayout:
a = Path(filename).stat().st_size
root = FloatLayout()
left_hand_side_offsets = FloatLayout()
leading_zeros = len(str(a))
top = 1
for i in range(0,a+1,16):
if i > MAX_ROWS_LOADED:
break
left_hand_side_offsets.add_widget(Button(text=f'{i:X}'.rjust(leading_zeros,'0'),color=TOP_OFFSET,size_hint=(.3,.03),pos_hint={'top': top}))
top -= .03
root.add_widget(left_hand_side_offsets)
return root
def build(self):
return self.hex_view('Win10_22H2_EnglishInternational_x64.iso')
in kivy i want to make it so that i can scroll pass the left hand side offsets
but it gets cut off near bottom
im probaly gonna have to implement it myself arent i
is there anyway i can detect if a widget is off screen or nah
Would be with a Scroll or Recycle View
im gonna put this off for now, right now im just trying to get the buttons instead of squishing together just get cut off if theres not enough space
def hex_view(self,filename: str | Path) -> FloatLayout:
a = Path(filename).stat().st_size
root = FloatLayout()
left_hand_side_offsets = FloatLayout(size_hint=(1,.5),pos_hint={'top':1})
leading_zeros = len(str(a))
OFFSET_LEFT_HEIGHT = .03
top = 1
for i in range(0,a+1,16):
if i == 0:
left_hand_side_offsets.add_widget(Button(text='Offset (h)',color=TOP_OFFSET,size_hint=(.3,OFFSET_LEFT_HEIGHT),pos_hint={'top': top}))
top -= OFFSET_LEFT_HEIGHT
continue
if i > MAX_ROWS_LOADED:
break
left_hand_side_offsets.add_widget(Button(text=f'{i-16:X}'.rjust(leading_zeros,'0'),color=TOP_OFFSET,size_hint=(.3,OFFSET_LEFT_HEIGHT),pos_hint={'top': top}))
print(left_hand_side_offsets.children[0].pos)
top -= OFFSET_LEFT_HEIGHT
root.add_widget(left_hand_side_offsets)
return root
look its squished
i just want it to but cut off into a void or something
i think ill have to implment this myself
There is Stencil to cut out, and can oversize the Layout.
If you have a runnable example - can see what the minimal changes would be with what you have
class HexView(FloatLayout):
def __init__(self,filename: str | Path,**kwargs):
self.filename = filename
super().__init__(**kwargs)
def on_size(self,*_):
a = Path(self.filename).stat().st_size
leading_zeros = len(str(a))
try:
self.remove_widget(self.left_hand_side_offsets)
except AttributeError:
pass
self.left_hand_side_offsets = BoxLayout(orientation='vertical')
max_amnt = int((self.size[1] // 58.18181818181818)*16)
for i in range(0,max_amnt+1,16):
if i == 0:
self.left_hand_side_offsets.add_widget(Button(text='Offset (h)',color=TOP_OFFSET,size_hint_x=.3))
continue
self.left_hand_side_offsets.add_widget(Button(text=f'{i-16:X}'.rjust(leading_zeros,'0'),color=TOP_OFFSET,size_hint_x=.3))
self.add_widget(self.left_hand_side_offsets)
print(self.size)
how would i make the offsets left fixed size
i want it to stay the same size when i make it wider but
it becomes wider
does anyone know how to make widget genratation in kivy faster? cause i need to make around 250 widgets at once but its too slow
only make widgets when absolutely nesxary and change values on widgets instead
dont make it soo often basically
250 ain't anything heavy
There must be something else going on
using qml, how to make an item invisible but keeps its size and placement ?
I've managed to do it by putting said item into another item with a size. That way, the layout can still figure out the placement wheiter or not its content is visible or not.
what do you call on this thing in notepad font window where
if you fill up the entry, it auto searches in the option list down below
and if you click something in the option, it fills up the entry
Two separate events
Yh maybe with some lock to stop the click fill refiltering the results
Depending on how the toolkit works
does anyone know how can i register key presses using tkinter?
you can use the .bind() method
ok ill try
some resources on binding to events like keyboard presses:
tutorial (scroll down to "Binding to Events"): https://tkdocs.com/tutorial/concepts.html#events
Tk's introduction: https://tcl.tk/man/tcl8.6/TkCmd/bind.htm#M4
a list of keys you can bind to, such as <BackSpace>: https://tcl.tk/man/tcl8.6/TkCmd/keysyms.htm
also its kind of mentioned in the resources, but in case you're not clear about it, tkinter will only send keyboard events to widgets that have "keyboard focus" so you'll need to be careful with what you call .bind() on:
https://tcl.tk/man/tcl8.6/TkCmd/focus.htm
At any given time, one window on each display is designated as the focus window; any key press or key release events for the display are sent to that window.
https://tkdocs.com/tutorial/concepts.html#events
You can also set up an event binding on a toplevel window. When a matching event occurs anywhere in that window, the binding will be triggered.
from what i can tell, some widgets like Text and Button automatically receive focus once you click on them, but other widgets like Label can't be focused on unless you manually trigger focus with the.focus_set()method
here's a demo if you want to play around with it: https://paste.pythondiscord.com/BUCA
Hi i am creating Build of my project
problem ===> size of the build is too much........
query === > i am using pyinstaller library to build , I am using only camera functionality of openCv and the size of the build is 56 MB
is there any practice to reduce down this size or can we extract the particular functionality of the opencv and use only this small functionality in our code so that the space it covers get reduced
Script===>pyinstaller --onefile aiii.py
Code
`import cv2
import numpy as np
class ai:
cap = cv2.VideoCapture(0)
def __init__(self,val):
self.assign=val
def calling(self):
while True:
_, frame = ai.cap.read()
print("heheheheheheh",_)
print(frame)
hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
if self.assign=='red':
low_red = np.array([161,155,84])
high_red = np.array([179, 255, 255]) ##in this array we are defining hsv values
red_mask = cv2.inRange(hsv_frame, low_red, high_red)
red = cv2.bitwise_and(frame, frame, mask=red_mask)
cv2.imshow("Frame", frame)
cv2.imshow("Red", red)
if cv2.waitKey(33) == 27:
# for i in range(6):
# val=input('yes/no: ')
# fn()
break
exit(0)
#main
print('what colour would you like to test')
print('1. Red /n Blue /n Green /n Yellow /n Orange /n pink /n brown ')
def fn():
value=(input())
# ref=ai(value)
ref= ai(value)
# for i in range(6):
ref.calling()
# permission=input('yes/no: ')
# if permission.lower()=='no':
# break
fn() `
:incoming_envelope: :ok_hand: applied timeout to @winged valve until <t:1709202172:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Hey community! I'm new to programming as well as Python... I'm really looking for a coding mentor, I have some ideas that I want to get started on but I really don't know what I'm doing that's why I joined this discord. I need help in building a user interface for an autonomous system not sure how to even approach it... any help would be dear
:incoming_envelope: :ok_hand: applied timeout to @robust hamlet until <t:1709297822:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
any one want help in tk/ctk can msg me
:incoming_envelope: :ok_hand: applied timeout to @loud patrol until <t:1709365651:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:ok_hand: applied timeout to @digital rose until <t:1709372736:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:ok_hand: applied timeout to @teal sundial until <t:1709394487:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:incoming_envelope: :ok_hand: applied timeout to @elfin lark until <t:1709417706:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:incoming_envelope: :ok_hand: applied timeout to @fossil root until <t:1709419093:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
You gonna have to live with that or find some lightweight opencv replacement
The thing is, the 56mb contains the opencv binaries which you can't just strip off of
:incoming_envelope: :ok_hand: applied timeout to @digital rose until <t:1709463215:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
hi Why python is little used in the graphics part
cool
Because the web is the present and future. Desktop apps are basically dying
Python web frameworks are just honestly bad
eeh
:incoming_envelope: :ok_hand: applied timeout to @digital rose until <t:1709500816:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
i dont get this, as the web could mean anything which sends data between machines.
and any work making for example wasm code system agnostic, could be work on making some system agnostic system call abstraction no?
id say that pythons small use in graphics is due to it being a bottleneck in the cpu part of graphics rendering processes
in that case, python is a really good example of a operating system and hardware agnostic system
i guess software distribution is handled by sending ( compiled wasm binaries?) in wasms case on the web, or just javascript
there are also some excellent software managers out there though, such as gnu guix which allows you to inspect the source code of all software on your system, down to the handwritten binaries which bootstrap the process
:incoming_envelope: :ok_hand: applied timeout to @neat hound until <t:1709524687:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
:incoming_envelope: :ok_hand: applied timeout to @autumn niche until <t:1709550205:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
in kivy what do i do so that i can display special unicode characters like \u263A
it just displays as that missing box with a X in it
Is it available in the font you're using?
If that character isn't available in the current font, it'll default to the box with an X in it.