#user-interfaces
1 messages · Page 85 of 1
you can put your classes in different modules, and import them to base module
Ohk,
I tried to import it but I get the circular import error
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main_flixgen.py", line 29, in __init__
for F in (StartPage, Page1, page2.Page2):
AttributeError: partially initialized module 'page2' has no attribute 'Page2' (most likely due to a circular import)
PS C:\Users\GAMER\Desktop\Python_School_Script>
wait a sec
i think i see what i can fix
U can do that, the thing is that u allso import tkinter there
yeah ik
😅
sorry that sounds kinda rude haha
Not rude, i thought u were asking
Yeah, im not sure how to get across the circular import
can you show your scripts :)
Sure
I think its in a cycle of importing
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from page2 import Page2
from page1 import Page1
from startpage import StartPage
LARGEFONT = ("Verdana", 35)
class tkinterApp(tk.Tk):
# __init__ function for class tkinterApp
def __init__(self, *args, **kwargs):
# __init__ function for class Tk
tk.Tk.__init__(self, *args, **kwargs)
# creating a container
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# initializing frames to an empty array
self.frames = {}
# iterating through a tuple consisting
# of the different page layouts
for F in (StartPage, Page1, Page2):
frame = F(container, self)
# initializing frame of that object from
# startpage, page1, page2 respectively with
# for loop
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
# to display the current frame passed as
# parameter
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
# first window frame startpage
# Driver Code
app = tkinterApp()
app.mainloop()
Page 1
import tkinter as tk
from tkinter import ttk
from startpage import StartPage
import page2
LARGEFONT = ("Verdana", 35)
# second window frame page1
class Page1(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Page 1", font=LARGEFONT)
label.grid(row=0, column=4, padx=10, pady=10)
# button to show frame 2 with text
# layout2
button1 = ttk.Button(self, text="StartPage",
command=lambda: controller.show_frame(StartPage))
# putting the button in its place
# by using grid
button1.grid(row=1, column=1, padx=10, pady=10)
# button to show frame 2 with text
# layout2
button2 = ttk.Button(self, text="Page 2",
command=lambda: controller.show_frame(page2.Page2))
# putting the button in its place by
# using grid
button2.grid(row=2, column=1, padx=10, pady=10)
Page 2
import tkinter as tk
from tkinter import ttk
from page1 import Page1
from startpage import StartPage
# third window frame page2
LARGEFONT = ("Verdana", 35)
class Page2(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Page 2", font=LARGEFONT)
label.grid(row=0, column=4, padx=10, pady=10)
# button to show frame 2 with text
# layout2
button1 = ttk.Button(self, text="Page 1",
command=lambda: controller.show_frame(Page1))
# putting the button in its place by
# using grid
button1.grid(row=1, column=1, padx=10, pady=10)
# button to show frame 3 with text
# layout3
button2 = ttk.Button(self, text="Startpage",
command=lambda: controller.show_frame(StartPage))
# putting the button in its place by
# using grid
button2.grid(row=2, column=1, padx=10, pady=10)
Use main statement when u import tkinter in ur program module
Start Page
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import page2
from page1 import Page1
LARGEFONT = ("Verdana", 35)
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# label of frame Layout 2
label = ttk.Label(self, text="Startpage", font=LARGEFONT)
# putting the grid in its place by using
# grid
label.grid(row=0, column=4, padx=10, pady=10)
button1 = ttk.Button(self, text="Page 1",
command=lambda: controller.show_frame(Page1))
# putting the button in its place by
# using grid
button1.grid(row=1, column=1, padx=10, pady=10)
# button to show frame 2 with text layout2
button2 = ttk.Button(self, text="Page 2",
command=lambda: controller.show_frame(page2.Page2))
# putting the button in its place by
# using grid
button2.grid(row=2, column=1, padx=10, pady=10)
Sorry how could I do that
Whoa so many
Haha 4 files 👀
In my projeacts i packed all classes in to a single file
Yeah ig i could do that, but it would prolly become too crowded in the end for me
Hmm if u have import structure like a tree where there is no loopong of two files importing eachother then u can ise
if __name__ == '__main__': import xyz
oo
but then it says the module isnt defined
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 51, in <module>
app = tkinterApp()
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 29, in __init__
for F in (StartPage, Page1, Page2):
NameError: name 'StartPage' is not defined
Hmm there moght be issue like that
Then what you can do os that u can make those imports out from ur main statement
could you please give an example
oh
Ohk just a sec i give u diagram what i am saying
so the easiest solution here is to import the module, and not the object directly
thats not the best solution, but the easiest possible here
a powerful website for storing and sharing text and code snippets. completely free and open source.
so instead of
from page1 import Page1
# does something with Page1
do
import page1
# does something with page1.Page1
see that fix
yes
but it uses from import
i have modified it
only in main.py
Oh
okay
same goes for other files
I see
see this if you are curious
https://stackoverflow.com/questions/22187279/python-circular-importing
Haha hope u understand it
Ur code seems lie at first it says in file a, import b and file b at first kine says import a, then in file a it says import b and thing continues like that
Wait I have a last question, If I want to for example change the geometry of the window, how could I do that?
like window.geometry("50x50")
how could I do that here?
I really say i dont remember that much but i know i have used it in my tutorial files
Aha thats okay
https://youtu.be/NytF3pJSMc8 see this
In this video I'll show you how to resize a window dynamically with Tkinter and Python!
We already know how to change the default size of our tkinter window:
root.geometry("800x800")
But how do we update that size after the program starts running? Since the dimensions are passed into the function surrounded by quotation marks, we have to ac...
I learned tkinter from his playlist
Haha I dont mean that
I understand how to resize it and stuff
but because we are using classes
No just watch the tutorail there he tells the code in between
Root is same as tk.Tk()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
root = tk.Tk()
root.geometry("500x500")
# label of frame Layout 2
When I do that it opens a new window
I think to resize u use same code but u change dimensions
Im not talking about that
Im taking about
root
because when i do root = tk.Tk()
and change its geometry it opens a new window
Im trying to ask what is this already set as
as its opeaning a new window
I see u have different structure, in your classes try asking billyeatcookied
He definitely have answer for u
Okay tysm
||@indigo crane sorry for the ping || If I want to forexample resize the window what would the tk.Tk() be equal to?
resize your window? that's a default behavior unless you have configured it
Yeah so for example if I want to do that what would I need to do?
a window is resizable by default
you don't have to do anything other than normal instantiation
Yeah so for me
what would it be?
so I want it
so when I switch frames the gui changes size
and I will set the size
you can modify geometry of the window using .geometry()
yeah so what would i put before .geometry()
but when i do that
it opens a new window
import tkinter as tk
from tkinter import ttk
import tkinter
from PIL import Image, ImageTk
from page2 import Page2
from page1 import Page1
from startpage import StartPage
LARGEFONT = ("Verdana", 35)
class tkinterApp(tk.Tk):
# __init__ function for class tkinterApp
def __init__(self, *args, **kwargs):
# __init__ function for class Tk
tk.Tk.__init__(self, *args, **kwargs)
# creating a container
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# initializing frames to an empty array
self.frames = {}
# iterating through a tuple consisting
# of the different page layouts
for F in (StartPage, Page1, Page2):
frame = F(container, self)
# initializing frame of that object from
# startpage, page1, page2 respectively with
# for loop
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
# to display the current frame passed as
# parameter
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
# first window frame startpage
# Driver Code
app = tkinterApp()
app.mainloop()
So in here
if i wanted to resize it
what would i do
you can resize it using root.geometry("widthxheight")
for example root.geometry("300x600")
root isnt defined and when I define it, it opens a new widnow
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 19, in __init__
app.geometry("500x500")
NameError: name 'app' is not defined
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 53, in <module>
app = tkinterApp()
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 15, in __init__
app = tkinterApp()
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 15, in __init__
app = tkinterApp()
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 15, in __init__
app = tkinterApp()
[Previous line repeated 496 more times]
RecursionError: maximum recursion depth exceeded
When I move it close to the top
oh
you will have to do it here
app = tkinterApp()
app.geometry("300x600")
app.mainloop()
right after definition, and before entering the loop
or you can also do it inside your class
Does it go in the init
then it says app.mainloop is not defined
import tkinter as tk
from tkinter import ttk
import tkinter
from PIL import Image, ImageTk
from page2 import Page2
from page1 import Page1
from startpage import StartPage
LARGEFONT = ("Verdana", 35)
class tkinterApp(tk.Tk):
# __init__ function for class tkinterApp
def __init__(self, *args, **kwargs):
# __init__ function for class Tk
tk.Tk.__init__(self, *args, **kwargs)
# creating a container
app = tkinterApp()
app.geometry("500x500")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# initializing frames to an empty array
self.frames = {}
# iterating through a tuple consisting
# of the different page layouts
for F in (StartPage, Page1, Page2):
frame = F(container, self)
# initializing frame of that object from
# startpage, page1, page2 respectively with
# for loop
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
# to display the current frame passed as
# parameter
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
# first window frame startpage
# Driver Code
app.mainloop()
This is the code im using
I tried to define app as well out of the init
but then it doesnt run the file
nvm eventually it gets this error
Traceback (most recent call last):
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 54, in <module>
app = tkinterApp()
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 19, in __init__
app = tkinterApp()
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 19, in __init__
app = tkinterApp()
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\new_main.py", line 19, in __init__
app = tkinterApp()
[Previous line repeated 493 more times]
no need to define app inside init
do self.geometry()
When I try to load an image onto it, it doesnt show up and there is no error
backgroundImage = tkinter.PhotoImage(
file=r"data\img\main_img\main_startpage.png")
backgroundImageLabel = tkinter.Label(self, image=backgroundImage)
backgroundImageLabel.place(x=10, y=10)
never mind i needed to make all the vars self.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\GAMER\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\page2.py", line 112, in <lambda>
command=lambda: tictactoe.play(), borderwidth=0)
File "c:\Users\GAMER\Desktop\Python_School_Script\new_test\tictactoe.py", line 235, in play
backgroundImageLabel = tkinter.Label(menu, image=backgroundImage)
File "C:\Users\GAMER\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 3148, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\GAMER\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2572, in __init__
self.tk.call(
_tkinter.TclError: image "pyimage16" doesn't exist
What does this error mean?
I made sure that hte image is there in the folder
(please ping n response ty)
Don't know much about the topic but it says to set 'master' kwarg in PhotoImage method
Almost done my first project creating a gui and I have a couple of questions
Is there any way for me to remove the borders on the buttons to make it look cleaner?
Also is there any way to shrink how much space there is at the top?
When ever I drag the window to shrink it, it always just cuts off the bottom and not the top
@digital gale Which library are you using?
PyQT5
Is that what it looks like when you run the python code or when you run the UI in QtCreator/Designer?
Using the preview function in QT Designer
Okay
Look at the main layout in designer, then set the top margin to 0
if its default still, it should say (12,12,12,12)
top is the second value
left,top,right,bottom
Are the numbers displayed on a label up there at the top?
What do you mean?
Yes
set the vertical size policy to maximum on that label
Sorry if im being a bit dense but im doing this im Property Editor correct?
Just did
okay, it should have shurnk a bit... did it?
Now I don't know where to find this
It probably says Form or Widget SomeLayout(GridLayout,HBoxLayout)
Nope
can you send me a screenshot of what the UI looks like in the designer window and include the widget tree on the right hand side?
Were you talking about these?
okay
So, see how centralWidget has the crossed red circle?
That means you don't have a layout on that widget
Right click on centralWidget, go to the layout menu, and choose layout in grid
Okay
so what changed when you did that?
Did you mean left click?
Right click brings up a menu
yeah, you should see an option near the bottom that says something about layout
it should open a submenu when you hover over it
Nope
hang on, let me open something up in the creator
Are you sure you right clicked on centralWidget?
Yes
Those options look like a right click on mainWindow
Its the opposite
Clicking on main window brings up what you want
Clicking on central widget doesn't
^ Is main Window
Oh, I guess thats a special behavior for mainWindow/centralWidget
normally when you add a widget and put something inside of it, you have to click on the widget, not its parent
anyway... what does it look like now?
Which layout do you think would look best for this?
I tried to use them once and completely failed
you have to do grid
perfect
now click on the layout, set the spacing to 0, and the contentsMargins to 0
How would I click on the layout?
all of the contentsMargins should be 0
if you don't see a layout, click on centralWidget and scroll to the bottom of the properties
Alright these are the options
yeah, set the 9s and 6s to 0
Looks like this now
click on one of your buttons and see what the size policy is set to
okay, use the property tree above the properties to select all of your buttons
then go down to the properties and try changing the size policy to Expanding,Preferred
What do you mean by property tree?
Select all also selects the label but im guessing I can change that later
You can control click single widgets to select more than one at a time
or maybe its shift, I don't know what it would be on windows
Okay, so at this point it might be easiest to manually set a minimumHeight on the label
when the label expands downwards the buttons will square up
you could try setting the vertical size policy to preferred, but you might have to break the layout
I will keep it as is
Is there not a way to make it borderless though?
I have seen it done before with PyQT5
I'd increase the font size in the label or make the entire thing a little bit wider so you can make the label smaller but keep buttons square
I personally like it the way it is
You can make it frameless but its a pain to implement, and I don't know how or if you can do it within designer
when you make it frameless, you have to override the mouse events just so you can move the window on your screen
I read it but it didnt work ty tho
That does seem like a pain
One last question
Is there any way to remove this bar?
thats done with the remove status bar option in the right click menu on mainwindow or centralwidget
Thank you for all your help!
or actually... you might just need to select the central widget in the property tree and then drag the little blue dots on the top and bottom of the widget if that doesnt work
drag them towards the window frame
Nope it just right there in MainWindow
that got rid of the space at the bottom and top?
ah, well if it show up when you run the python code, you know what to do
I will
Thank you for all your help. I just need to finish my EXP button logic and I will be on my way to making my first post on github
Nice! good luck with the project.
Hey, I found a code on the Internet which ask me to select an excel and then it displays it on my UI, but as I want to display always the same excel, is there a way to automatically choose the same excel?
In fact what I want to do is to display an excel on my tkinter ui
hey, I got a Qt QMainWindow class and I want to separate all the functions (except the init) from the class into another file, how can I do that?
there are many functions in the class, and the file is getting a bit large
basically I want to define the class and it's initialization, like button presses, combo box changes, etc in one file and all of it's functions that are called by the buttons, text changes, etc separate into another file
if I can separate them into multiple files it would be awesome
you can define the GUI in a QMainWindow class and then subclass that to implement your behaviour
Thanks @rocky dragon I'm gonna try this!
Hello, i've designed an application in QT designer and then converted it into Python code, When i run it, it run okay on my laptop but when i try to run it on the raspberry pi, It crashes
it was working before, I just added a new QStackedWidget page and some Slider and labels after which it stopped working
Hello is it possible to make a rounded window in tkinter? like for windows 10 for example with rounded corners
pls ping if you respond
well.. i use pysimplegui which is easier and have things called popups, popups have a property called no_titlebar which is as it name suggest removes title bar which makes customization it easier i think but this is NOT REALEATD TO MUCH about TKINTER OR YOUR QUESTION
haha thank you for your comment tho
try it i recommend it if u have time for a small learning curve(im not fluent in english lol)
wow really? your english is really good 😅 alr i will look into it
ok thx
ok i know rules but try googling it i will try to find a useful website i didnt say must.(so i didnt break the rules as i think)
the custom treeviews ive been working on, its almost usable now :)
Hello, I'm trying to finish my UI but the code isn't working but the syntax seems right
Here's the code :
And this is weird bcs I made a former UI that worked I just copied and pasted it
This one works perfectly
forgot to close your round bracket on frame004 side
menubar = tk.Menu(self)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=self.donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.quit)
for me New and exit are like so close to edges
there is no inner padding or margine
i wanna make it like above shown in SS
padding in left and right
and keep the text in center
Which one out of the three is the best looking pls
Which one out of the three is the best looking pls
sorry if its in wrong chat
the third one
np
Hello I have a question
# Import module
from tkinter import *
root = Tk()
root.geometry("900x600")
canvas = Canvas(root, width=900, height=600, bg="white")
canvas.pack()
#my_rectangle = round_rectangle(50, 50, 150, 100, radius=20, fill="blue")
canvas.create_rectangle(170, 0, 900, 600)
# Create transparent window
root.attributes('-alpha', 0.7)
# Execute tkinter
root.mainloop()
How can I make it so that the canvas isnt also invisible kinda
like i want it to stand out
any idea why im only getting red colors out of this? (pls ping)
newColorBase = [randint(0,360),uniform(.70,.99)]
print(newColorBase)
dimColor = tuple(round(i * 255) for i in convColor(newColorBase[0],newColorBase[1],.70))
brightColor = tuple(round(i * 255) for i in convColor(newColorBase[0],newColorBase[1],.99))
print(dimColor)
areaFinder.colors.append(("#%02x%02x%02x" % dimColor, "#%02x%02x%02x" % brightColor))```
import PySimpleGUI as sg
import time
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
#Just creating the layout for the window
layout = [
[sg.Text("Please Enter The Text You Would Like Typed")],
[sg.InputText()],
[sg.Submit()],
[sg.Cancel()]
]
#setting the window size and putting it into a variable
window = sg.Window("Python Auto Typing System", layout,margins=(250,250))
#opening the window up
event, values = window.read()
while True:
time.sleep(1)
if event == "Cancel":
break
else:
print(values[0])
window.close()
Trying to make a GUI for a future autoclicker but the problem is if I try to use a while loop to continuselly preform one command until cancel is clicked it crashes
I don't want the program to stop until cancel is clicked but if I don't but event, values = window.read() it will crash, if I do put it in there it will stop every time it executes the command
I'm developing a software that would allow me to write the phonetic respelling (with english alphabets) of lexemes for non-indoeuropean languages to then convert them to a fitting translation of lexemes written in the native language.
Now i've finished the logic of the translation and the base system but I'm unsure of how to implement the GUI utility that would allow me to use it diversely independent of the software.
Optimally I imagine something like a system that I can enable, write the payload in any application and the system will be able to replace it inside wherever I'm writing in, is it possible? if not what other alternatives should I take?
Hello someone help me I have a problem in my code with tkinter I made a login page and it was supposed to open another page when I clicked on the login button but in the background it's giving error "_tkinter.TclError: couldn't recognize data in image file "background2.png"" how can i fix this?
Try something like
img = ImageTk.PhotoImage(Image.open(background))
@livid shell
Tkinter bind:
What should be the string argument for ctrl+space key in bind function
<Control_L-<space>>
How is my UI for password manager application
good one 👍
Anyone here using PyGObject?
thanks for the review
If you change the bg=“white” to a different color?
Hello All
I am just wondering... which gui framework should i choose?
Nah that doesnt work
I do recommend PyQt
I tried it. It does have a lot o controll over the gui. BUT it is not easy to learn (Where do i start?)
Tkinter or Kivy
and with kivy you can use KivyMD for better interfaces
They have their own uses honestly. Tkinter is better for flexibility,
Here is Kivy vs Tkinter and how they differ
actually I used the both
Tkinter is very very basic
but
if you want more beautiful GUI kivy is the best
and also
with Kivy you can create a mobile app
.apk
Kivy doesn’t work on Linux it looks like
True, just looked it up. That image I sent isn’t correct then lol. Googles wrong
Kivy has limitations though when it comes to developing mobile apps though, right? I believe I’ve read before that people recommend not writing apps in python because native/kotlin and c/swift provides much more options on what you can do.
yes of course
native apps are more better and performent
but if we talk Python
Kivy is the best
Understood!
stupid question but when in pycharm the console at the bottom can it be made to be a seperate window?
Which library should I learn for simple-ish desktop applications?
I just created my first application in PyQT5 but I found the designer hard to use
Tkinter or Kivy
I don't think so
Does kivy have a designer? I feel like it would be complicated hard coding everything
yes, it's a hard coding library
I think you want just drag and drop things right ?
Not entirely but I would prefer not having to write all of the design elements
hmm I understand
there is one
if you wanna try it
"Pygubu"
its is a python GUI for building tkinter apps
How hard is it to make applications with kivy?
Maybe I'm over estimating how much I would have to hard code because of pyqt5
A simple calculator gui was 2.6k lines
And it glitched out my pycharm
wow HAHAHAHAHAHA
Why are you guys using pycharm for small tasks and projects ?
use VSCode or vim either
Pycharm is for big big projects
Theres nothing wrong with pycharm
My system can handle it just fine
No point of not using it
It also has better intellisense than vsc
try this one
@brisk plank Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
Hello everyone, I'm in the process of doing a gui that should reads the feed of a camera and does some image processing tasks such as an fft. To do so, I've decided to go for pyqtgraph since it's amazingly fast and does an exceptional job at real time stuff. However, I'm having a hard time finding documentation on it. For example now my problem is how to control the ROI, the 1D plot at the bottom, the side slider and change the colormap. One thing that would be useful would be to set a ROI that allows to extract two crossed lines to get the transverse profiles of the image. If anyopne could point me to some examples that do this I would really appreciate it
https://github.com/pyqtgraph/pyqtgraph/blob/master/pyqtgraph/examples/ROIExamples.py and https://github.com/pyqtgraph/pyqtgraph/blob/master/pyqtgraph/examples/ROItypes.py
Whats the best way to use sound in tkinter , pygame or playsound or etc
I have made game in tkinter and for soundeffects o want to dd sound to it
And a bg music
_tkinter.TclError: invalid command name ".!frame.!treeview"
Why am I getting this error?
I m getting this on
frame2.destroy()
global frame2
frame2 = Frame(root)
frame2.pack(pady = 20)
# Create a Treeview widget
global tree
tree = ttk.Treeview(frame2)
Part of the code
also #help-cherries
am knew to discord and have questions about utf-8, is this a good place for it
?
😒
does QT work cross-platform? The same code i write for linux works on windows without the user needing python installed?
Qt is a cross platform framework, but you will need python
at least when you're using the python bindings
does anyone know if there's a way to detect keypresses without the user pressing return (like arrow keys, etc) in the terminal? i'm making a tui with rich and am looking for something similar to curses' getch.
Is there any way I can get this to work for windows? https://github.com/bchao1/bullet
Can Anybody please help me in embedding a PyqtGraph into a PyQt QFrame widget?
What are you trying to use? It shouldn't be any different than adding any other widget.
import numpy as np
from pyqtgraph.Qt import QtWidgets
from pyqtgraph.imageview import ImageView
app = QtWidgets.QApplication()
frame = QtWidgets.QFrame()
view = ImageView()
img = np.random.randint(0, 255 + 1, size=(256, 256, 3))
view.setImage(img)
layout = QtWidgets.QVBoxLayout()
frame.setLayout(layout)
layout.addWidget(view)
frame.show()
app.exec_()
This is how i created my frame inside the mainWindow Class (PySide2),
self.temp2_page_mainFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.temp2_page_mainFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.temp2_page_mainFrame.setObjectName("temp2_page_mainFrame")```
Now i want the following example graph from pyqtgraph.examples to be embedded into this frame
```import pyqtgraph as pg
import numpy as np
from time import perf_counter
import time
win = pg.GraphicsLayoutWidget(show=True)
win.setWindowTitle('Temperature Plot')
chunkSize = 100
# Remove chunks after we have 10
maxChunks = 10
startTime = perf_counter()
win.nextRow()
p5 = win.addPlot(colspan=2)
p5.setLabel('bottom', 'Time', 's')
p5.setXRange(-10, 0)
curves = []
data5 = np.empty((chunkSize + 1, 2))
ptr5 = 0
def update3():
global p5, data5, ptr5, curves
now = perf_counter()
for c in curves:
c.setPos(-(now - startTime), 0)
i = ptr5 % chunkSize
if i == 0:
curve = p5.plot()
curves.append(curve)
last = data5[-1]
data5 = np.empty((chunkSize + 1, 2))
data5[0] = last
while len(curves) > maxChunks:
c = curves.pop(0)
p5.removeItem(c)
else:
curve = curves[-1]
data5[i + 1, 0] = now - startTime
data5[i + 1, 1] = np.random.normal()
curve.setData(x=data5[:i + 2, 0], y=data5[:i + 2, 1])
ptr5 += 1
def update():
update3()
timer = pg.QtCore.QTimer()
timer.timeout.connect(update)
timer.start(50)
if __name__ == '__main__':
pg.exec()
Note: The graph example code is in a different .py file, I will need to import this into my main.py file where the frame is.
Thanks for your help
I guess you'd import win from whichever example that is and add that to the layout that your frame uses
File "main.py", line 73, in cmd
if e1.get and e2.get in line:
TypeError: 'in <string>' requires string as left operand, not method
Error ^^
def cmd():
for line in response.split('\n'):
if e1.get and e2.get in line:
messagebox.showinfo("LOGIN SUCCESSFULLY", " W E L C O M E ")
q=Tk()
q.mainloop()
else:
messagebox.showwarning("LOGIN FAILED"," PLEASE TRY AGAIN ")
Code ^^
can anyone help me regarding this issue?
what should i make as a string
What is the proper way of switching pages while using Eel? What im trying to do is redirect from login to dashboard page on an successful login attempt.
Atm i'm doing it by triggering the following js method js function logged_in_js(){ window.location.href="dashboard.html"; }
but im not sure if this is the right way to do.
ive made a pretty goof text user interface and how do i make a next page without having a indentation
import tkinter as tk
def on_enter(e):
myButton['background'] = 'green'
def on_leave(e):
myButton['background'] = 'SystemButtonFace'
root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()
myButton.bind("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)
root.mainloop()
@ashen oar
no im talkin bout
ok ill give an example
when i hover on the start button
it moves diagonally up
and there will be a shadow where the shadow button is rn
but idk how it will go diagonally up
and im not talking it just goes diagonally up
i want like an animation with it
Idt u can do that in tkinter
i don't get what you really want, but using threading and some images it should work
the animation isn't gonna be super smooth tho
what framework do u guys recommend for gui ?
In python - tinker or a wrapper around it, called pysimplegui . These should be more than enough for most graphic interfaces.
By default, tkinter is already downloaded with py3.X . Usually shortened to tk .
If you're just starting out, or need a basic gui - pysimplegui would do.
Its beginner friendly, and shortens some calls of tkinter and help creating the interface faster.
r there any ways to decrease the distance between the content n the window border in pyqt6?
(using layouts if tat's the prob)
layout.setContentsMargins(0,0,0,0)
okay thx
i would also like to know how to change the color of the scroll bar (the blue thingy) using stylesheets
QScrollBar::handle:vertical {
background: #123;
}
oh wow thx a loot
@eager beacon can you help?
hi! i have come across some problem which i can't really figure out the solution of... so. I am making a music player (similar to MusicBee) and i really want to achieve fade in and fade out effects after unpausing and pausing... the thing is that i want to keep my ai responsive while doing that (the fades would not be longer than like 0.6 s). For sound output I'm using QAudioOutput and QMediaPlayer for player. I tried multithreading with QThread, trying to keep my main window responsive, but it's not working as i want to and i got some errors which i don't really know how to fix, even after thorough google search. The thing is that i have two functions that would gradually set volume lower during the designated fade period (0.6 seconds max) and that bugs my ui when i try pausing or unpausing during that time. If any of you have come across a problem like this, I would really appreciate your help! :)
Hi, I need some help with handling pyqtgraph inside PyQt5. Since I'm a newbie in pyqtgraph, I decided to do a small "hack" so as to be able to handle better the positioning of the plots. So I want to place 4 plots in a grid of 2x2, and what I did was to wrap a PlotItem inside a QWidget, and then use a QGridLayout since I already some familiarity with that layout. This is how I defined my new Plot widget:
class LinePlot(QWidget):
def __init__(self):
super().__init__()
self.global_layout=QVBoxLayout(self)
self.global_layout.setContentsMargins(0,0,0,0)
#Create line plots
self.plot=pg.GraphicsLayoutWidget(self)
self.plot.setContentsMargins(0,0,0,0)
self._plot=pg.PlotItem()
self.line=pg.PlotDataItem({"x": [],
"y": []}, pen=pg.mkPen('g', width=1))
self._plot.addItem(self.line)
self.plot.addItem(self._plot)
self.global_layout.addWidget(self.plot)
However, I'm now experiencing a somewhat serious problem: if I resize my window with all these plots, even if I'm not updating them in real time, or have anything plotted on them, it may crash my app. I assume that this may not have happened if I had used the pyqtgraph native layout system, but I could really use some input
@wary birch pyqtgraph.GraphicsLayoutWidget allows easy grid layouts. see for example pyqtgraph/examples/scrollingPlots.py
@wary birch however, using pyqt layout widgets should be fine; I use QGridLayout all the time.
@wary birch it really is worthwhile to run all the pyqtgraph examples as you're starting out; get a sense of what's possible, and then know to go look at the source when you want to build something similar.
Hi does anyone know how to do a simple login page with pysimplegui and like create buttons to bring it to the other function
db = mysql.connect(host="localhost",user="root",password="",database="attendance")
command_handler = db.cursor(buffered=True)
def main():
while True :
print("Attendance")
print("")
print("Teacher?")
print("Admin login")
option = input(str("Teacher or an Admin? : "))
if option == "Teacher":
teacher()
elif option == "Admin":
admin()
else:
print("Incorrect")
Anyone pls tell me how to add a boxplot to tkinter..
Use matplotlib
line should be a list or something
i tried but having issue with it
Tried using canvas and matplotlib
Can u pls guide me.?
im not sure, how
fig = Figure(figsize = (5, 5), dpi = 100)
plot2 = fig.add_subplot()
y = df['Year_of_Release']
data = without_Year_of_Release_outliers
data1 = [y, data]
box_plot_data = (y, data)
plot2.boxplot(box_plot_data)
canvas = FigureCanvasTkAgg(fig, root)
canvas.draw()
canvas.get_tk_widget().place(x = 490, y = 330)
This is my code, but it is not showing in tkinter
I can plot in my normal jupyter notebook or any other Python IDE but not able to show in tkinter
Can someone pls help
What is the best way to get a date from the user in Tkinter? I would like it to look something like this: https://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml5_input_type_date
There is a library called tkcalendar that has tools made for this
@brisk sable ^
Thanks! I'll look into that.
how would I go about making a tkinter row at the bottom of the screen? Im using grid()
i have a QTextEdit and how can i add line numbers beside? (using pyqt6)
Ugh. at job we faced a problem of having lack of satisfaction with current UI
This book looks interesting to read perhaps: Tidwell J. Designing Interfaces. Patterns for Effective Interaction Design 3ed 2020
At least it has the best score / big rating / having enough demand to be already 3 edition.
+Fitting to be read even by developers.
https://www.amazon.co.uk/dp/1492051969?linkCode=gs2&tag=oreilly20-21
Who This Book Is For
We hope Designing Interfaces reaches current and new audiences. We created it to be
of interest and value to many different people. It’s for design beginners, mid-career
practitioners and managers, seasoned professionals, and executives. It’s for people
who want to learn, to get a refresher, and to get inspiration and a new point of view.
It’s for teams, classes, and individuals. It’s for interaction designers, information
architects, product designers, UX/UI designers, product managers, developers, QA
engineers, strategists, managers, leaders, consultants, teachers, students, and anyone
who is interested in designing better software
Perhaps anyone knows even better book to recommend?
I have a database and I am using PysimpleGui I would like to know how I can separate the names in the ListBox
you should use replit though
how can i make a user agreement thing when they start my game like they have to click a field with i accept the user agreement and then click next
like this

Does anybody know How to open up the QT virtual Keyboard when QlineEdit is Focused/Clicked?
heyy
from tkinter import *
import numpy as np
ui = Tk()
ui.geometry('300x200')
ui.title('Quadratic Equation')
entry_space_x = Entry(ui, width=10, borderwidth = 5)
entry_space_x.pack()
entry_space_y = Entry(ui, width=10, borderwidth = 5)
entry_space_y.pack()
entry_space_z = Entry(ui, width=10, borderwidth = 5)
entry_space_z.pack()
entry_answer = Entry(ui, width = 50)
entry_answer.pack()
def calculate():
a = float(entry_space_x.get())
b = float(entry_space_y.get())
c = float(entry_space_z.get())
entry_answer.delete(0, END)
try:
d = np.sqrt(b**2 - 4*a*c)
except RuntimeWarning:
entry_answer.insert(0, "roots not found")
except:
entry_answer.insert(0, "unexpected error")
x1 = (-b+d)/(2*a)
x2 = (-b-d)/(2*a)
entry_answer.insert(0, f"answers are {str(x1)} and {str(x2)}")
calculate_button = Button(ui, text = 'Calculate', command = calculate)
calculate_button.pack()
ui.config(bg = "#808080")
ui.mainloop()
why is try and except here not working at all?
it's just returning "nan" for both values
Someone help me my code is giving an error when the page updates with the part of "window.update(background)"
error: "TypeError: Misc.update() takes 1 positional argument but 2 were given"
how can I solve? because if I remove the background it no longer gives an error but the page updates and gets buggy
Hello does anyone know a way I can do something like this?
where the background is blurred tkinter btw
which i can do with root.attributes('-alpha',0.5)
but I want the canvas to not be blurred or is it possible to gove a canvas attributes
||Please ping on response||
Is there a way I can disable/gray out an entire frame in Tkinter?
Hey @spare garnet!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
!code-blocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
INFO]: Prebuilding Pillow for armeabi-v7a
[INFO]: Pillow has no prebuild_armeabi_v7a, skipping
[INFO]: Applying patches for Pillow[armeabi-v7a]
[INFO]: Applying patch patches/fix-setup.patch
[INFO]: -> running patch -t -d /content/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/Pillow/armeabi-v7a__ndk_target_21/Pillow -p1 -i /content/.buildozer/android/platform/python-for-android/pythonforandroid/recipes/Pillow/patches/fix-setup....(and 270 more)
Exception in thread background thread for pid 57993:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.7/dist-packages/sh.py", line 1683, in wrap
fn(*rgs, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/sh.py", line 2662, in background_thread
handle_exit_code(exit_code)
File "/usr/local/lib/python3.7/dist-packages/sh.py", line 2349, in fn
return self.command.handle_command_exit_code(exit_code)
File "/usr/local/lib/python3.7/dist-packages/sh.py", line 905, in handle_command_exit_code
raise exc
sh.ErrorReturnCode_1:
RAN: /usr/bin/patch -t -d /content/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/Pillow/armeabi-v7a__ndk_target_21/Pillow -p1 -i /content/.buildozer/android/platform/python-for-android/pythonforandroid/recipes/Pillow/patches/fix-setup.patch
STDOUT:
patching file setup.py
Hunk #1 FAILED at 29.
Hunk #2 FAILED at 317.
Hunk #3 FAILED at 567.
Hunk #4 FAILED at 647.
Hunk #5 FAILED at 717.
Hunk #6 FAILED at 769.
6 out of 6 hunks FAILED -- saving rejects to file setup.py.rej
STDERR:
this is the .spec requirnments
(list) Application requirements
comma separated e.g. requirements = sqlite3,kivy
requirements = python3,Kivy==2.0.0rc4,Pillow,kivymd==0.104.2,requests,urllib3,chardet,idna
can anybody help
???????
from kivy.app import App
from kivy.uix.label import Label
class myApp(App):
def build(self):
and return its instance
return Label(text = "Ahmet'in İlk Mobil Projesine Hoşgeldin")
if __name__ == "__main__":
myApp.run()
syntax error
how can i fix?
remove or comment that line
myApp().run()
In eel app, im experiencing some weird behavior compared to the PC im running it on. On 1 pc, switching html pages works fine, but on the other one im getting the This site cant be reached error.
why without layouts?
idk
hmm
I want more control
over the widgets
ig
but yes later like after 1 week me gonna learn grid layout
cause it is gonna be my main layout ig
well is it possible ?
probably if you handle the repositioning manually, definitely would be easier with a scrollable layout in the widget
ok
can you send a link or a example ?
I am assuming cli related stuff will also be asked here. So basically I need to choose a library for the cli parsing and another library for sweet terminal progress-bars and table display. In a way I would prefer to keep dependencies to a minimum so I dont end up with more libs related to cli stuff then the actual program.
For cli, I need ability to nest parser/commands and let parsers written in another file "register" themselves and extend the cli seamlessly.
For the cli parsing, the options I could find were
argparse (python stdlib, I remember having a horrible time with subparsers)
docopt (does not seem exactly maintained or "extendible")
cleo (no idea, but seems to provide a lot of stuff and used by poetry too)
click (seems to be popular, used by httpx)
typer (click but with typehints instead of decorators I guess?)
No idea if I am forced into using progressbars and colours and stuff of one of the last 3 libs or I can use rich/tqdm/etc ones.
For pretty terminal I would prefer good looking and one I can control without poking around too much. The ones I had found are,
tqdm
rich
alive-progress
- colorama obviously
I haven’t used any, but Rich, Textual and Colorama are mentioned often
how to create really beautifuls tools(software GUI)? module? please ping if you response
hello friends! = )
pyqt5 question -
is it possible to embed/show a QWidget inside of a QGraphicsView / QGraphicsScene (however that works)
basically, my app works like this -
- i have my main pyqt5 app. using a menu option, i popen a subprocess, grab its window handle, and shove that external window into a QWidget.
- from there i am placing that widget into a tab in a QTab, and can present the external app properly (effectively embedding that subprocess into my app)
- i am then layering in some object detection, and "drawing" the matches back onto the subprocess window housed in my main app (think overlays), using additional transparent and click-through-able colored QWindow objects
if possible, i would like to instead trade the QTab for a QGraphicsView/Scene, so i can have better control over the drawing of the overlays
i have also considered using QStackWidget/Layout, but have not been able to get it to work properly.
any advice is welcomed! 🙂
Hello
tkinter question
i have a jarvis and i need make a gui for this but when i try to make a gui first it runs gui and when i close gui it opens jarvis but i want to run gui and jarvis at the same time i can share codes anyone can help ?
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import keyboard
import time
from tkinter import *
from PIL import ImageTk,Image
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Seni dinliyorum...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Söylediklerini tanımlıyorum...")
query = r.recognize_google(audio, language='tr-TR')
print(f"Kullanıcı şunları söyledi: {query}\n")
except Exception as e:
print("Tekrar eder misin ?")
return "None"
return query
uyg = Tk()
uyg.maxsize(width=1200, height=700)
uyg.minsize(width=1200, height=700)
uyg.mainloop()
@rocky dragon I remember you working with pyside6 stubs. I'm setting it up on a work laptop and trying to get VSCode to recognize the stubs. The page for pyside6 stubs feels... well incomplete.
Do you remember what you did to get your IDE to recognize the stubs?
nevermiiind, my browser was glitching and not loading the rest of the page
Is this an appropriate space to ask a question about interface options
Is PyQt the "best" for a begginer?
i used pyqt designer to build a really really simple app
but i want to expand it, make something like this with various tabs on the left side
Qt isn't exactly beginner-friendly, but it is the best overall. So if you've already started using it and you're happy with it, there's no point learning another framework, there's nothing they can do that Qt can't
hey guys im new to python and have to create a gui calculator using tkinter
https://pastebin.com/phFPfQJ2
thats what ive done but i havent created 2 buttons that are supposed to do cm - inch / inch - cm conversions and I also have to make the background a light blue colour, im unsure of how to do this and where to insert those things into my code. the tutorials i watched werent very clear to me as the way each person was creating their calculator was different. I have to have this created by in the next 12 hours so any assistance would be really appreciated. its been giving me a headache lmao
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hm ok, and should i use designer? or code everything myself?
any python packages you guys would recommend for having draggable elements on a canvas?
good question
(I'm not familiar with Qt, but I've used designers for other GUI stacks)
A designer is a timesaver for making apps quickly and it's also a great learning tool, if you pay attention to a few things:
- The Property menus are great for finding out what's possible, use them to experiment with stuff. They'll teach you what properties a widget has, so it will be easy to find them again when you're writing code directly.
- Make a habit of reading the code generated by the designer, so you know what does what and you'll feel comfortable editing it if needed.
- Paradoxically, the weak point of designers is layout. When you drag a widget to some place on the screen, and drag its corners to resize it, the designer doesn't know your intent: did you want an absolute position, or aligned with something else? what should happen if the content becomes too big, or the user resizes the window? You'll need to learn widget positioning and reflowing yourself, so you can make changes if the designer doesn't do what you want.
Hello I'm experiencing some issues regarding PyQt5.
Code: https://paste.ofcode.org/Mh3ipd8dXBjEHDMzgQua2C
I have four QLineEdit()'s where the user will enter a data,
I have one QPushButton() where the user's data will be transferred to the Calculation class.
Everything goes very well until line 116 where the UiTable() is called, the table itself is never shown for some reason. There are no errors but the debug prints is showing that it goes well 
I think it might be that I call self.show() two times, once in line 43 and once in line 149. If that's the issue, how would this be solved?
Any kind of help will be appreciated, if you want to run the script yourself to see what's going on, feel free to do so! 😛
what would recommend, Dearpygui or Pysimplegui?
They are quite different, so it depends on what you need. What are your requirements?
Dear PyGui supports this. For example, see
https://github.com/Magic-wei/DearBagPlayer#drag-to-plot
It also provides a node editor, see
https://github.com/hoffstadt/DearPyGui/wiki/Dear-PyGui-Showcase
oo dearpygui actually looks like my best bet, instead of duct-taping tkinter extensions into a pysimpleguitk or pysimpleguiwx thing
I wouldn't know about the other libraries, but Dear PyGui supports it. Another basic example @prisma cloak
https://github.com/Mstpyt/DPG-Examples/blob/main/drag_and_drop_project_chart.py
(should work, I haven't tried)
Be sure to check out the API documentation
https://dearpygui.readthedocs.io/en/latest/index.html
Discord is best for support
https://discord.gg/tyE7Gu4
After installing Dear PyGui, be sure to run the built-in demo. It has an example of drap and drop as well.
https://dearpygui.readthedocs.io/en/latest/tutorials/first-steps.html#demo
I wouldn't recommend pysimplegui.
As soon you get beyond something completely trivial, the code becomes an ugly mess of nested lists.
It uses tkinter or qt behind the scenes, but doesn't do a very good job of covering all their features, so you may need to learn both pysimplegui, the framework underneath it, and how to get the two to play nice.
The documentation is very imcomplete.
Hey, im using PyQt to make an GUI app for windows. I need to have a visually transparent window that doesn't allow clicking other apps through the transparent regions, how would i do this?
setWindowFlags(Qt.FramelessWindowHint) setAttribute(Qt.WA_TranslucentBackground)```These two flags are enough for transparency but it has the forementioned problem
Possible workaround but seems kinda clunky, having background color on all elements with very low opacity seems to capture all the mouse events
Is it possible to package a kivy app for windows on linux. I've been trying to follow the official instructions, but the package kivy_deps doesn't seem to exist for linux.
Hi, I'm using Qt and I have a QThread with a worker containing an infinite loop. But when I close my window, the worker obviously doesn't end. What should I do to properly end my worker and its thread ?
I don't use linux, so I don't really know what's going on. However, after digging around, I think this may help:
I am learning Kivy and following this article https://realpython.com/mobile-app-kivy-python/ I am getting this error. It would be helpful if the explanation is lucid. Os: macOS Big Sur, I am using a
I'm trying to visualize the date field of my code with QDateEdit, but the program doesn't display anything, can anyone help?
def data_cat ():
data=str(validade.dateEdit_2.selectedDate())
print(data)
Hi I am using Tkinter for creating a program, I want that when I click a button, it change the whole screen, I tried using frames, but in he first page I have already used four frames for four buttons, so it is not working please help
Hi, in pyqtgrapgh, how do I make the viewbox occupy the whole widget? That is, I want to remove that black padding
Here's the code:
class widget(QWidget):
def __init__(self):
super().__init__()
self.global_layout=QVBoxLayout(self)
self.global_layout.setContentsMargins(0,0,0,0)
self.plot_main=pg.GraphicsLayoutWidget(self)
self.plot_main.setContentsMargins(0,0,0,0)
self._plot_main=pg.PlotItem()
self._plot_main.layout.setContentsMargins(0,0,0,0)
self.img=pg.ImageItem()
self._plot_main.addItem(self.img)
self.plot_main.addItem(self._plot_main)
self._plot_main.hideAxis("left")
self._plot_main.hideAxis("bottom")
# self._plot_main.disableAutoRange()
data=np.random.random((100,100))
self.img.setImage(data)
self.global_layout.addWidget(self.plot_main)
Nvm, I found it. Had to go to the internal Qt layout and use .setContentsMargin(0,0,0,0) within the GraphicsLayoutWidget
Am I correct that creating tkinter.Variables is not thread-safe? 😬
because this is what it does ```py
global _varnum
...
else:
self._name = 'PY_VAR' + repr(_varnum)
_varnum += 1
so if I create two variables in two separate threads, there's a chance that they will get the same name, right?!
I guess I can pass my own name and guard the generation with a lock or something
also, nice debugging print... https://github.com/python/cpython/blob/main/Lib/tkinter/__init__.py#L390-L392
Lib/tkinter/__init__.py lines 390 to 392
for name in self._tclCommands:
#print '- Tkinter: deleted command', name
self._tk.deletecommand(name)```
hey, I have a very basic question regarding UI. How do you design UI for any software? Should I be using some UI design apps like figma? How do i integrate figma ui with python code?
Hello I would like to do a ui with tkinter so open programs with buttons do you have any suggestions?
when i want to open the programs it doesn't find the path
I used kivy it’s hard to grasp at first then it gets better, lots of features but little documents regarding help, the documentation is good though
I’ve seen that lambdas are typically used to pass extra arguments through Qt slots. I’m just curious as to why a lambda is need to pass ANY arguments. Is it simply because Qt just ignores whatever argument you put inside the slot function and that’s just how it is?
a lambda is a callable, calling a function ie func(args) would just assign the returned item
Hi guys, I am using tkinter. Would you say this is a bad layout?
How could I improve it?
(the add button would create a new block every time you press it)
Depends on the average use case. If a lot of blocks are added, it would become difficult to navigate since it would be a lot of scrolling and no visual distinction between blocks
One alternative is to show a modal or separate page when adding a new device, which shows the form for that device. The device will get added once that form is filled in and the user pressed some submit button.
You could then add a dropdown menu with a search bar to select a certain device to view details of, edit, or delete.
But if you only anticipate like 3-4 devices then your layout is probably okay, except perhaps for the inability to delete a specific device.
anyone here well-versed with PyInstaller?
Sorry, would you be able to expand on that?
!e
x = lambda: print(123)
x()
y = print(123)
print(y)
@tribal path :white_check_mark: Your eval job has completed with return code 0.
001 | 123
002 | 123
003 | None
things like slots or commands in tk take callables, ie x and are called with () based on say the signal
I just started making GUIs and I ran into a small issue when trying to make my first own GUI using tkinter. The program is supposed to make a window in which there is a counter that starts from 0 and it goes up and down and resets with "Increase", "Decrease" and "Reset" buttons. Additionally the window closes and the program stops running from "Quit" button.
The GUI is made with the following code:
class Counter:
def __init__(self):
self.__main_window = Tk()
self.__number = 0
self.__current_value_label = Label(self.__main_window, text=f"{self.__number}", relief=FLAT)
self.__current_value_label.pack()
self.__reset_button = Button(self.__main_window, text="Reset", borderwidth=2, relief=RAISED, command=self.reset)
self.__reset_button.pack(side=LEFT)
self.__increase_button = Button(self.__main_window, text="Increase", borderwidth=2, relief=RAISED, command=self.increase)
self.__increase_button.pack(side=LEFT)
self.__decrease_button = Button(self.__main_window, text="Decrease", borderwidth=2, relief=RAISED, command=self.decrease)
self.__decrease_button.pack(side=LEFT)
self.__quit_button = Button(self.__main_window, text="Quit", borderwidth=2, relief=RAISED, command=self.quit)
self.__quit_button.pack(side=LEFT)
self.__main_window.mainloop()
And the methods it calls inside the commands are as follows:
def reset(self):
self.__number = 0
def increase(self):
self.__number += 1
def decrease(self):
self.__number -= 1
def quit(self):
self.__main_window.destroy()
Right now the counter inside the window doesn't get updated from the buttons. There must be something wrong with the contains of the methods. Quit works just fine.
How would I go about making something similar to Unreal Engine's event editor in python? (basically a canvas on which you can place blocks and connect them with "wires")
Hey guys. I'm a noob and not really sure how to ask this question so bear with me. I know it's somewhat common for desktop gui applications to be written in HTML/CSS/JS nowadays. (I'm referring to like Electron) - is there any easy way to stack something like that on Python? Even some more narrow Google search terms would help me out because I can't find a thing
This seems to be popular https://github.com/ChrisKnott/Eel
You'd probably be better off just using electron if you're set on using JS
@raven tundra if you're looking for something like the declarative views in React and still want to be able to use Python you should check out QML
Thank you!
I'm thinking of doing something like this, which if I limit to 10 devices, hopefully scrolling won't be an issue
and then I can add ability to delete devices or edit their details next to each block
I was just worried about it being unusable or looking like a mess
ok ok
what are they called
icons
Example #1
iconphoto(self, default = False, *args)
Example #2
program.iconbitmap('<image path>')
Example #3
program.tk.call('wm','iconphoto',program._w,tk.PhotoImage(file=’<image path>'))
err
idk
they should do the ones at the bottom too?
the ones at the bottom use the window icons don't they?
.bm
I'll try them as well
Does anyone work with kivy before?
I would like to know can kivy drop the GIL in multithreaded code? While I want to do some image processing stuff, but don't want to make GUI unresponsive at that time, I want to visualize with wheel movement in the UI so that to make understand that something happening or processing at the background. So can kivy drop the GIL in multithreaded code?
I think you are looking for a node editor. The Dear PyGui framework has support for node editors built in. There is a bit of a learning curve, but it's possible. See the following two implementations as examples.
Example 1: a simple example (compatible with the latest version of the API)
https://github.com/hoffstadt/DearPyGui/wiki/Dear-PyGui-Showcase#heron-a-hybrid-approach-to-data-pipelines-in-python
Example 2: an extended example (not compatible with the latest version of the API)
https://github.com/hoffstadt/DearPyGui/wiki/Dear-PyGui-Showcase#interactive-assembly-line-balancer
I have not heard aobut that before. What did you have in mind?
Dear PyGui has its own theming system.
well. the dear pygui framework seems to have a very specific design, unlike UI frameworks like tkinter or qt which follow your system's GTK settings
You are right about that. Dear PyGui renders everything itself, independent of the OS. You can change the fonts, colours, rounding, spacing, etc. to change the look of an app, but it will not inherit the settings of the OS.
yikes
do you happen to know how to accomplish what I'm looking for with Qt or TKinter or any other framework that does follow the OS?
Qt might have a node editor as well. I wouldn’t expect Tkinter or WxPython to have a node editor. @rain quarry
Qt doesn't have a node editor but there is a super nice one on github https://github.com/jchanvfx/NodeGraphQt
Hi, saw your question.
There is actually a way to change the bottom icon on the taskbar in windows.
Let's assume that you have a very simple tkinter code:
from tkinter import *
root = Tk()
root.mainloop()
You can see the default icon on your taskbar.
Next, simply put your ico icon file in the same folder as your python file.
Add the following code at the very start of your program:
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(YOUR_ICO_ICON_FILE_NAME)
You can then see the icon on your taskbar changed to your ico file icon.
Hope it helps! :D
i have this gui but when i maxximize it the rest of it turns white
how can i fix this?
can you post the code?
ok
import tkinter as tk
from tkinter import filedialog, Text
import os
root = tk.Tk()
canvas = tk.Canvas(root, height=700, width=700, bg="#36393F")
canvas.pack()
root.mainloop()
Sorry, had to run afk
You can do it with canvas.pack()
I think this will do it but i'm not able to test it right nowcanvas.pack(fill='both', expand=True)
alr
@ebon vine Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
.bm
Thank you!!
np
How can I display html content in my gui? So if I would be making my own webbrowser
Qt provides a text widget with some html support, or its webengine that I believe uses chromium
Ah ok nice thanks
Assuming you are using python tkinter, there are two options:
Tkinterweb. If you are viewing simple websites, this will be the best option. Simply install it using pip install tkinterweb. A simple program will go like this:
import tkinterweb
import tkinter as tk
root = tk.Tk()
frame = tkinterweb.HtmlFrame(root)
frame.load_website(YOUR_WEBSITE)
frame.pack(fill="both", expand=True)
root.mainloop()
Warning: The websites you visit will simply look like in IE or worse.
Cefpython. Something that I think will fit your needs, cefpython is a full-blown chromium browser embedded in Tkinter. An example can be found here: https://github.com/cztomczak/cefpython/blob/master/examples/tkinter_.py. Sadly, it does not work on newer versions of python so I couldn't test it out.
Extracted from: https://stackoverflow.com/questions/52436214/add-web-browser-window-to-tkinter-window
Thanks, Ig I will stick to qt tho since I want the websites to look good
alr
(pyside2) I have a lable with an editable flag, how can I capture when an edit has been made
label = qtw.QLabel(parent)
label.setStyleSheet(
"QLabel {\n"
f" background: {'#3B674C' if isinstance(process, Trigger) else '#435776'};\n"
" color: white;\n"
" width: 130px;\n"
" padding: 3px;\n"
" border: 1px solid #3B674C;\n"
" border-radius: 10px;\n"
"}"
)
label.setText(process.title)
label.setTextInteractionFlags(qtg.Qt.TextEditorInteraction)```
Hi, so sorry I do not have any experience with pyside2. I'll try my best to help though.
I've dug through the docs and I think this may help: https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QLabel.html#PySide2.QtWidgets.PySide2.QtWidgets.QLabel.setTextInteractionFlags
If not, I also came across this question while researching which may help: https://stackoverflow.com/questions/23370261/pyqt-check-if-value-of-qlabel-changed
Once again, I'm so sorry if this answer is not useful - but I hope it is.
I've put snip in column 40/100, but it keeps going outside of the window, why is this happening?
if I put it to 50/100, it completely goes to the otherside of the window and causes problems there
can i see code?
snipbutton = PhotoImage(file = 'snipbutton.png')
s_btn = Label(image = snipbutton, borderwidth = 0)
s_btn.grid(column = 40, row = 1)
root = Tk()
root.title('SnipOCR')
root.geometry('600x190')
canvas = Canvas(root, width = 600, height = 190, highlightthickness = 0)
canvas.grid(columnspan = 100, rowspan = 100)
canvas.configure(background = '#303030')
root.resizable(False,False)
root.iconbitmap('logosnip.png')
blueberry = PhotoImage(file = 'blueberry.png')
img = Label(image = blueberry, borderwidth = 0)
img.grid(column = 50, row = 99)
text = PhotoImage(file = 'text.png')
text_img = Label(image = text, borderwidth = 0)
text_img.grid(column = 45, row = 55)
mt = PhotoImage(file = 'ny.png')
mt_img = Label(image = mt, borderwidth = 0)
mt_img.grid(column = 50, row = 55)
snipbutton = PhotoImage(file = 'snipbutton.png')
s_btn = Label(image = snipbutton, borderwidth = 0)
s_btn.grid(column = 40, row = 1)```
ok giveme a sec to test it brb
um.. do you mind if you can send the whole folder including the photos im having trouble with the photos on my end
i'll dm it to you
alr
it's very helpful thank you very much! :)
Glad to hear that!
pls help..idk what to do..i just bought new laptop and now moving my projects and i cant install wxpython..it works fine on my old laptop...where python is 3.9.5
ok i got it...new python is the problem...so i am using 3.9.5 now
Electron is an HTML based GUI for Python.
use tkinterhtml
btw u cannt make webbrowser with tkinter html
use selenium for local html (gud for webbrowser i think)
self.home = QPushButton("Home", self)
self.home.setStyleSheet("QPushButton { margin-top: 5; border: none; border-top: 2 solid #ccffcc; border-radius: 10; color: white; } QPushButton:hover { background: #ffccff; color: black; }")
self.home.setToolTip("Home")
self.prev = QPushButton("<-", self)
self.prev.setStyleSheet("QPushButton { margin-top: 5; border: none; border-top: 2 solid #ccffcc; border-radius: 10; color: white; } QPushButton:hover { background: #ffccff; color: black; }")
self.prev.setToolTip("Prev")
self.next = QPushButton("->", self)
self.next.setStyleSheet("QPushButton { margin-top: 5; border: none; border-top: 2 solid #ccffcc; border-radius: 10; color: white; } QPushButton:hover { background: #ffccff; color: black; }")
self.next.setToolTip("Next")
Why they are on top of each other?
this is PyQt5
Hi, Im watching a pyqt5 tutorial and I dont understand:
sys.exit(app.exec())
Ik what sys.exit does but now why we pass the app.exec() func?
For websites what would be a good "human test" to bar account creation? Preferably it would be done without using external services and would be something I can make a lot of variations on to avoid bots being able ot just put in the same answer every time to get past.
Hi, how can I make my gui scale in PyQt5? So when resizing the window my widgets also resize
set a layout on the windows widget and put the widgets yyou want to scale inside that layout
The app.exec(), or app._exec() if you are using Python 2, starts up the event loop and will block until the application quits [see attachment]. If an exit code has been set, exec()will return it after the event loop terminates.
If I'm correct you are asking a question on websites. Head to #web-development , this is not the right channel.
using PySide6
code:
import sys
from PySide6.QtWidgets import *
app = QApplication(sys.argv)
win = QWidget("Hello World")
win.show()
app.exec_()
error:
Found invalid metadata in lib C:/Users/babario/anaconda3/Library/plugins/platforms/qdirect2d.dll: Invalid metadata version
Found invalid metadata in lib C:/Users/babario/anaconda3/Library/plugins/platforms/qminimal.dll: Invalid metadata version
Found invalid metadata in lib C:/Users/babario/anaconda3/Library/plugins/platforms/qoffscreen.dll: Invalid metadata version
Found invalid metadata in lib C:/Users/babario/anaconda3/Library/plugins/platforms/qwindows.dll: Invalid metadata version
qt.qpa.plugin: Could not find the Qt platform plugin "windows" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
what i did to install pyside6
pip install PySide6
NOTE: i hv pyqt6, pyqt5 intalled, is tat the problem?
okayy thx
I am struggling like hell to get QTableView and QTreeView to resize to the data in any nice way:
-
best setting to just get those Widgets to resize the columns and the rows to the data?
-
is there a way to get it to resize to the data and also have it be able to resize interactively? When the user clicks and drags the border between columns or rows
There is QHeaderView.ResizeToContents but it seems mutually exclusive to QHeaderView.Interactive.
What I need would be a way to initially (or when new data is added) to resize it to content and then have it resizeable interactively.
When replying please KEEP the Ping, so I get notified
i just started using tkinter, and i made a type racer
import tkinter as tk
from tkinter import *
import random
import time
with open('list1.txt', 'r') as f:
a = f.readlines()
text = ""#makes a random sentence of 25 words from the list1.txt file
for i in range(0,25):
word = random.choice(a)
word = word[:-1]#the file return a list containing the words with \n at the end
if i == 24:
text += word+"."
elif i == 0:
text += word.capitalize() + " "
else:
text += word+" "
count = 0
count1 = 1
timercount = True
start_time = 0
def spell_check(*args):#this function is activated whenever a change in the entry is detected
global count,count1,timercount,start_time
if timercount:#i made this so that it only starts when the user starts to type
start_time = time.time()
timercount = False
if len(var.get()) - count == -1:#changes color to black when using backspace
count -= 1
count1 -= 1
text_label.tag_add(f"start{count}", f"1.{count}", f"1.{count+1}")
text_label.tag_config(f"start{count}", foreground="black")
else:
if var.get()[-1] == text[count] and len(var.get()) == count1:#checks if the letter is correct
text_label.tag_add(f"start{count}", f"1.{count}", f"1.{count+1}")
text_label.tag_config(f"start{count}", foreground="green")
elif var.get()[-1] != text[count] or len(var.get()) != count1:#checks whether the word is wrong
text_label.tag_add(f"start{count}", f"1.{count}", f"1.{count+1}")
text_label.tag_config(f"start{count}", foreground="red")
count += 1
count1 += 1
if var.get()[-1] == "." and len(var.get()) == len(text):
end()
lps = 1
def end():
global lps
lps = len(text)/(time.time()-start_time)
window.destroy()
root = Tk()
root.geometry('400x200')
label = Label(root, text=f"your total speed was : {round(lps,2)} letters per second")
label.pack()
root.mainloop()
window = Tk()
window.title("Type Racer")
window.geometry('700x600')
text_label = Text(window)
text_label.pack()
text_label.insert(INSERT,text)
var = StringVar()
var.trace_add("write", spell_check)
Entry(window, textvariable=var).pack(padx=5,pady=5)
window.mainloop()
how do i make it look good
and it doesnt count how many letters were wrong
You can style some tkinter widgets using the widgets in tkinter.ttk instead and the Style class
In tkinter, how can I attach some payload to a virtual event?
can you show an example?
Yes hold on I'm trying to make it interesting
Here, have a look at this.
from tkinter import Tk, Canvas, EventType
from time import perf_counter
def clamp(n: float, minimum: float, maximum: float) -> float:
return min(maximum, max(minimum, n))
def float16_to_color(n: float) -> str:
return f"#{0xffffff - int(clamp(n, 0, 16) * 0xffff) >> 1:06x}"
class Application(Tk):
def __init__(self, radius: float = 10) -> None:
super().__init__()
self.count: float = perf_counter()
self.last_x = None
self.last_y = None
self.radius: float = radius
self.canvas: Canvas = Canvas(self)
self.init()
self.mainloop()
def init(self) -> None:
self.canvas.pack(fill="both", expand=True)
self.event_add("<<Holding>>", "<Button-1>", "<B1-Motion>")
self.bind("<<Holding>>", lambda e: self.draw(e, perf_counter()))
def draw(self, event: EventType, count: float) -> None:
since: float = count - self.count
color: str = float16_to_color(since)
if self.last_x is None and self.last_y is None:
self.canvas.create_oval(event.x - self.radius, event.y - self.radius, event.x + self.radius, event.y + self.radius, fill=color, outline="")
else:
self.canvas.create_line(self.last_x, self.last_y, event.x, event.y, fill=color, width=10)
self.last_x = event.x
self.last_y = event.y
self.count = count
def main() -> None:
app = Application()
if __name__ == "__main__":
main()
You can improve it by setting self.last_x and self.last_y to None again in a B1-Release event
Maybe I don't understand something, but I was asking how to attach a custom payload to an event. Like: widget.event_generate("<<FileReady>>", custom_payload={"file_obj": ...})
I know how to handle events
but I can't pass arbitrary kwargs to event_generate
>>> root.event_generate("<<Foo>>", custom_data = 42)
...
_tkinter.TclError: bad option "-custom_data": must be -when, -above, -borderwidth, -button, -count, -data, -delta, -detail, -focus, -height, -keycode, -keysym, -mode, -override, -place, -root, -rootx, -rooty, -sendevent, -serial, -state, -subwindow, -time, -warp, -width, -window, -x, or -y
Maybe in data
I can't find any documentation on what data does.
Event objects also don't have a data field
I came up with this system where I bootleg an event ID via the x coordinate of the event in a thread-safe way... but it seems really overengineered
https://gist.github.com/decorator-factory/34c80257a750c1aafb5ea588a8296922
Basically, I maintain a dict mapping event IDs to payloads. When I want to emit an event, I increment a counter and use that counter to add a new entry to the dict. Then I place the counter value into the x coordinate (or maybe some other attribute of the event).
then I can do ```py
import tkinter as tk
from .virtual_event import VirtualEvent
root = tk.Tk()
@VirtualEvent.listen
def on_foo(event, numbers):
print(f"{event=} {numbers=}")
on_foo.bind(root)
button = tk.Button(root, text="Okay", command=lambda: on_foo.emit([1, 2, 3, 4, 5]))
button.grid(column=0, row=0)
root.mainloop()
``` and on_foo actually receives the list [1, 2, 3, 4, 5]
I understand that I can't put this payload directly into the event, because I can't transform between arbitrary Python objects and Tcl values. But I was wondering whether tkinter had some utility to help out with this
...also without memory leaks
right, I can technically extract the data field using some hack
but it will hold a string
. not some arbitrary payload
I'm working with PySide2.
I've added a small widget in the bottom left, but ideally it'd be styled the same as the contents of the tab widget (i.e. darker inside). How would I go about copying this without using a custom stylesheet?
And if that's not possible, how would I at least put a clear boundary around it
inheritance??
can someone help plz im a beginner making a pokedex and im struggling to display the images of the pokemon when you click their name in the listbox. As you can see in the pic of my pokemon image file, the pokemon are in in the same order as the names in the listbox and are also distinguishable by the first three numbers of their file name. How do I configure my image label to show whichever pokemon is selected in my clickevent function. I know theres a prtty simple solution im way too tired to see.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
heres the code so far dont mind its a bit messy from trial and error
Tkinter is not so good for making games. Why don't you try out pygame? If you still wish to use tkinter, please let me know and I will try to solve your problem.
For some reason this tab item isn't setting itself scrollable, any ideas how I can fix that? ```py
def add_tab_widget(self, name: str):
def get():
scroll = QtWidgets.QScrollArea()
scroll.setLayout(QtWidgets.QVBoxLayout())
scroll.layout().setAlignment(QtCore.Qt.AlignTop)
scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
getattr(self, f"configure_{name.lower()}_widget")(scroll) # Add child nodes
return scroll
self.tabs[name] = get # get is called when widget is added
and the code for that group: ```py
def config_iir_group(self, name, label, widget: NodeBaseWidget):
group = QtWidgets.QGroupBox(label)
group.setLayout(QtWidgets.QHBoxLayout())
groupA = QtWidgets.QWidget()
groupA.setLayout(QtWidgets.QVBoxLayout())
groupB = QtWidgets.QWidget()
groupB.setLayout(QtWidgets.QVBoxLayout())
a = self.node.coeffs_a
b = self.node.coeffs_b
current = a + b
def make_slider(_group: QtWidgets.QGroupBox, _name: str, index: int):
sub = QtWidgets.QWidget()
sub.setLayout(QtWidgets.QHBoxLayout())
sub.layout().addWidget(QtWidgets.QLabel(_name))
line_edit = QtWidgets.QLineEdit()
validator = QtGui.QDoubleValidator(-10, 10, 10)
validator.setNotation(QtGui.QDoubleValidator.StandardNotation)
line_edit.setValidator(validator)
line_edit.setText(str(current[index]))
def complete(*args, **kwargs):
arr = self.node.coeffs_a + self.node.coeffs_b
arr[index] = float(line_edit.text())
self.set_property(name, arr)
line_edit.editingFinished.connect(complete)
sub.layout().addWidget(line_edit)
_group.layout().addWidget(sub)
for i in range(self.order):
make_slider(groupA, "A" + str(i+1), i)
make_slider(groupB, "B" + str(i), i + len(a))
make_slider(groupB, "B" + str(self.order), 2 * self.order + 1)
scroll = QtWidgets.QScrollArea()
scroll.setWidget(group)
group.layout().addWidget(groupA)
group.layout().addWidget(groupB)
widget.layout().addWidget(group)
its not for a game its just the pokedex by itself, i do wana try pygame at some point but this task was set by my teacher lol
i made a little progress but still am not quite there https://pastebin.com/EW2k47Lr
So basically, I understand that you want to show the Pokémon selected on the ListBox on the right.
Step 1:
Getting the selected option on the listbox.
Before you .mainloop the program, add the code: root.after(0, yourFunctionToUpdatePokemon). This will call the function BEFORE the mainloop starts.
Step 2:
Creating the function.
def yourFunctionToUpdatePokemon():
while True: #We want to loop this
time.sleep(1) #Let's check every one second, you can change it if you wish to.
root.update() #Prevent the program form crashing.
for item in listbox.curselection(): #We get the index of the item selected
pass
# I don't know much about tkinter PhotoImage, but basically you can set the image name
# using this simple code
imageName = (str(str(int(item) + 1).zfill(3))+".png")
# then set the photoimage to the image name
Step 3:
Remove the M58 and stuff like that behind the image file name.
And done!
ah okay, thank you
Does anyone know the solution to my scrolling issue?
I've hit a brick wall on a tutorial of all things.
I'm going through the Qt tutorial stuff for use with PySide6 and I keep running into an error:
https://doc.qt.io/qtforpython/tutorials/qmlsqlintegration/qmlsqlintegration.html The tutorial (if I can get this working it'll be a good place for me to pick it apart and work from there)
The three files that it has you make in (listed in the following order) sqlDialog.py, main.py, chat.qml:
https://paste.pythondiscord.com/payokayaki.py
https://paste.pythondiscord.com/ejehowaroj.py
https://paste.pythondiscord.com/suniroyave.qml
The error it gives me is the following:
QQmlApplicationEngine failed to load component
file:///C:/Users/runner/Python/it_tickets/chat.qml:12:5: SqlConversationModel is not a type
I've hunted all over and I cannot get a straight answer.
Quick question, how could I create buttons like these with PyQT5?
When I say "like these" I mean when clicked they stay pressed sort of like a switch and when not pressed they are grayed out
I'm fine working with bare code or using the PyQT5 designer but I would prefer to use the designer for visualization and easier manipulation
You need to add import SqlConversationModel in the QML - this is what's causing the error
then, in ColumnLayout use anchors.fill: parent instead of window
there is also a typo in the ListView delegate
anchors.right: sendByMe ? listView.contentItem.right : undefined should be sentByMe, like in the property.
Use a QButtonGroup
I think you need to add scroll.setWidgetResizable(True)
still no scrollbar when it becomes too big :(
hmm.. let me try.
Yours is a bit more abstract but this is all you need to do to use a scrollArea.
import random
from PySide6 import QtWidgets
from PySide6.QtCore import Qt
class ScrollArea(QtWidgets.QScrollArea):
def __init__(self,parent=None):
super(ScrollArea, self).__init__(parent)
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
layout.setAlignment(Qt.AlignTop)
widget.setLayout(layout)
self.setWidget(widget)
self.setWidgetResizable(True)
class Widget(QtWidgets.QWidget):
def __init__(self,parent=None):
super(Widget, self).__init__(parent)
self.setLayout(QtWidgets.QGridLayout())
self.button = QtWidgets.QPushButton()
self.button.clicked.connect(self.add)
self.scrollArea = ScrollArea()
self.layout().addWidget(self.button)
self.layout().addWidget(self.scrollArea)
self.scrollArea.setWidgetResizable(True)
def add(self):
r = random.randint(1,200)
l = QtWidgets.QLabel(str(r))
self.scrollArea.widget().layout().addWidget(l)
app = QtWidgets.QApplication()
win = Widget()
win.show()
app.exec_()
Oh I need a setWidget instead of layout.addWidget, is that it?
scrollArea needs setWidget(someWidget). someWidget's layout is the layout that you will add widgets to when you move the slider
how to get this output from console to new window in tkinter?
def floydWarshall(graph): row_names = ["A", "B", "C", "D"] n = len(graph) dist = [[] for i in range(n)] for i in range(n): for j in range(n): dist[i].append(graph[i][j]) for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) print('Najkrotszy dystans pomiedzy kazda para') print("\033[91m A B C D\033[0m") for i in range(n): print("\033[91m{0}\033[0m".format(row_names[i]), end=' ') for j in range(n): if dist[i][j] == INF: print("%7s" % ("INF"), end=' ') else: print("%7s" % (dist[i][j]), end=' ') print()
this is my logic
Hi, Im using PyQt5 rn and I dont understand why the widgets are not getting shown on the layout.
Also when I try to print the children of the layout out its just an empty list.
def window(): app = QApplication(sys.argv) win = QMainWindow() layout = QHBoxLayout() layout.addWidget(QPushButton("Left-Most")) layout.addWidget(QPushButton("Center"), 1) layout.addWidget(QPushButton("Right-Most"), 2) print(layout.children()) win.setLayout(layout) win.show() sys.exit(app.exec())
You need to use setcentralwidget on win, then on that widget, set a layout and put the widgets in there
guys
im working on a project and im creating a menu
is any type of way to create an interface that looks cool? it would probably give me some extra credit on it
I dont understand, why does it not work this way? I copied the code but left out the class and it didnt work, before it was just a class inheriting from QWidget.
Its exactly the same code
Well, its not the exact same code though. Before it was a QWidget. You changed that to QMainWindow(). If you change it to QWidget() it would work like it did before.
QMainWindow lets you do a few things that, like a menu bar across the top off the window, status bar, and you can add dockWidgets to QMainWindow.
What do you mean by cool?
Something like this?
How do I make a pyside2 widget pop out in a new window? I tried just .show as the docs suggested but I couldn't get it to work.
def popout_widget(self, graph, node):
main = QWidget()
main.setLayout(QVBoxLayout())
widget = QTabWidget()
node.set_config_widget(widget) # adds elements to tabwidget
main.layout().addWidget(widget)
main.show()
I feel like that should work. Are you sure a signal is connected to that method?
not a signal but yes it's triggered
actually it might be a signal triggering this callback, not sure
Try renaming main to self.popup and see if that works.
yup, that did it
Okay, that makes sense
Usually when you open a window like that, its a QDialog, and its run with exec()
So if you want a fresh widget every time you trigger the method, you could make a list and stick it in an instance variable, then right after you create main, append main to the list
you can monkeypatch a closeEvent to call self.list.pop() to clear the list when you're done with the widget
it might not be the worst idea to use the pop() to run deleteLater() to make sure it actually gets deleted at some point
Ay
I'm a heavy Qt user and I was told tkinter was simpler. I just tried and I probably must have missed a few things because it was kinf od chaotic. Any good ressources for Tk users ?
Why use Tkinter if you know Qt?
If you're already familiar with Qt I think the only benefit to using Tkinter would be that it's stdlib
is there a ref for tkinter that is not the official website ?
Hello, I need some help with planning this app out.
I want to make an app that has an alarm, timer and all these functions.
My biggest problem right now is the alarm tab(frame).
I want the user to be able to create many alarms ( similar to iPhone clock app ), and every alarm will be in the same frame..
However, a clear problem with that is that the amount of alarms is dynamic, meaning I would need the labels, buttons and all these functionalities for each alarm to be created dynamically based on how many alarms the user has created. ( Alarms are stored in db )
In summary, how do I dynamically create buttons, labels utilizing some sort of loop in Tkinter and still keep the command functionality working properly?
I don't think there is, maybe docs for Tk itself but I'm not sure how useful those are compared to Tkinter's
You can still access effbot with the wayback machine. https://web.archive.org/web/20200703091947/http://effbot.org/tkinterbook
I learnt tkinter from him, it may be useful for you too.
https://www.youtube.com/c/Codemycom
Nice UI! (Just note that blueberry is already a company for screen recorder https://www.flashbackrecorder.com/aboutus)
why is it so difficult to find a real-time plotting library that's somewhat decently documented and doesn't have major issues...
If anyone has recommendations please do let me know, so far I've tried:
- matplotlib (too slow)
- pyqtgraph (mem leak and hates scaling)
- pythonqwt (ignores parent widget size)
- vispy (basically doesn't exist yet)
if pyqtgraph is fine otherwise and the widget was handled properly by you then I'd open an issue there and wait for the fix, the development seemed fairly active
Have you tried Dear PyGui?
Datoviz looks promising but still early stages
High-performance interactive scientific data visualization library
looks too much like imgui and I;m not a fan of the simplistic look it provides
doesn't seem to support qt
Sure.
thanks, what should I add to it?
Where's the memory leak in pyqtgraph?
I assumed PlotDataItem.setData but apparently not according to the dev's tests so I don't even know at this point
all I know is that calling this function is what causes the memory leak```py
def plot_signal(self, audio: np.ndarray):
for i, channel in enumerate(audio):
self.signal_plots[i].setData(channel)
I'd assume it's in the Node library.
how so? It's just a widget and it's not like there's two of them
Well, in my opinion, I think you can remove the fade in over here. It looks windows XP-ish.
You can add a image editor for your snips
cant say. I only glanced at the files.
I tired to build the app but I don't have a recent version of xcode
I followed your instructions and it said I need xcode 12, but thats not available on Mojave

Oh wait my setup.py is only configured properly for Linux isn't it
Not sure
Idk how Gradle works on mac
> Task :cinteropPythonNative FAILED
Exception in thread "main" java.lang.IllegalStateException: Unsupported Xcode version 11.3.1, minimal supported version is 12.5.
at org.jetbrains.kotlin.konan.target.AppleConfigurablesImpl.checkXcodeVersion(Apple.kt:85)
at org.jetbrains.kotlin.konan.target.AppleConfigurablesImpl.access$checkXcodeVersion(Apple.kt:24)
at org.jetbrains.kotlin.konan.target.AppleConfigurablesImpl$xcodePartsProvider$2.invoke(Apple.kt:63)
at org.jetbrains.kotlin.konan.target.AppleConfigurablesImpl$xcodePartsProvider$2.invoke(Apple.kt:54)
too bad that library isn't smaller
it would be easy to switch to PyQt5 and see if the leak is still there
have you tried running that function with some random data ?
go with PySide6
I can give that a try next
Its big enough that going from PySide2 to PyQt5 would be a pain. Making it compatible with PySide6 would be too much trouble just to see if it its the qt binding causing the issue
you should upgrade to either PyQt6 or PySide6 anyway, so... better sonner than never 😉
Qt6 and its PyQt6/PySide6 derivatives are the future... any serious developer should upgrade to Qt6 realm
what's the issue you're trying to solve, anyway?
memory leak
which version of Python and which exact version of PyQt are you seeing this?
what exactly leaks?
No clue
hmmm, got a code to work on?
Calling this function is what causes it
The code is at https://github.com/martmists-gh/kaudio-python
have you considered using the QtMultimedia module of PySide2?
@rain quarry Does it happen with the fft widget too?
yes
can I plot log graphs with that?
I don't see any classes it provides for plotting at least
oh, sorry, wrong module... QtMultimedia is for sound
Honestly, I think spending 5 minutes to change all of the Signals to pyqtsignal would be the best thing you could do
please read this article, it will give you great insight into plotting in PySide
use PyQtGraph by installing it: pip install pyqtgraph
that's the library I already use though
which has the memory leak issue
did you even read my problem lol
how exactly are you detecting the memory leak?
htop
here's the original video
ah, I see... just saw the video... but why do you think you're experiencing a memory leak just by having a huge memory usage?
please read this...
Updating the plot
While you can simply clear the plot and redraw all your elements again, this means Qt has to destroy and recreate all your QGraphicsScene objects. For small or simple plots this is probably not noticeable, but if you want to create high-peformance streaming plots it is much better to update the data in place. PyQtGraph takes the new data and updates the plotted line to match without affecting any other elements in the plot.
To update a line we need a reference to the line object. This reference is returned when first creating the line using .plot and we can simply store this in a variable. Note that this is a reference to the line not to the plot.
my_line_ref = graphWidget.plot(x, y)
because it keeps going up until my system runs out of memory
how exactly are you updating your plot?
effectively using my_line_ref.setData(yData)
To update a line, we need a reference to the line object. This reference is returned when first creating the line using .plot, and we can simply store this in a variable. Note that this is a reference to the line, not to the plot.
my_line_ref = graphWidget.plot(x, y)
Once we have the reference, updating the plot is simply a case of calling .setData on the reference to apply the new data.
yeah that's what I do
please read this Updating the plot section of the article
python_src/kaudio_app/nodes/util/visualizer.py line 104
def plot_signal(self, audio: np.ndarray):```
I have a feeling you're doing something wrong
What should I do with the buttons?
What do you mean
If that's the case I'd love to know what I'm doing wrong
please compare this code example with your own code...
PyQt5!
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtCore import QTimer
import pyqtgraph as pg
import sys
from random import randint
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.graphWidget = pg.PlotWidget()
self.setCentralWidget(self.graphWidget)
self.x = list(range(100)) # 100 time points
self.y = [randint(0,100) for _ in range(100)] # 100 data points
self.graphWidget.setBackground('w')
pen = pg.mkPen(color=(255, 0, 0))
self.data_line = self.graphWidget.plot(self.x, self.y, pen=pen)
self.timer = QTimer()
self.timer.setInterval(50)
self.timer.timeout.connect(self.update_plot_data)
self.timer.start()
def update_plot_data(self):
self.x = self.x[1:] # Remove the first y element.
self.x.append(self.x[-1] + 1) # Add a new value 1 higher than the last.
self.y = self.y[1:] # Remove the first
self.y.append( randint(0,100)) # Add a new random value.
self.data_line.setData(self.x, self.y) # Update the data.
app = QApplication(sys.argv)
main = MainWindow()
main.show()
app.exec_()
do I just replace all pyside2 imports with pyqt5?
yes
thank god it's that simple
Yeah, and all Signal with pyqtSignal
in the code example, there's no Signal needing to be changed to pyqtSignal
The code is more than what has been posted in this chat
but you can decorate the update_plot_data() method with Signal() (if using PySide) or pyqtSignal() (if using PyQt)
Slot()
did you even look at my codebase
TypeError: addWidget(self, QWidget, stretch: int = 0, alignment: Union[Qt.Alignment, Qt.AlignmentFlag] = Qt.Alignment()): argument 1 has unexpected type 'NodesPaletteWidget' @eager beacon
Is that coming from your python_src folder?
which is from from NodeGraphQt import NodeGraph, setup_context_menu, NodesPaletteWidget
hang on. Let me check something
is my code example working for you, @rain quarry ?
Can you try using 5.12?
This package follows version recommendations from here: https://vfxplatform.com/
VFX Platform : Reference Platform for VFX Software
Movie studios really hate bugs so they are always a couple of years behind on the newest version
$ pip install pyqt5
Collecting pyqt5
Using cached PyQt5-5.15.6-cp36-abi3-manylinux1_x86_64.whl (8.3 MB)
Collecting PyQt5-Qt5>=5.15.2
Using cached PyQt5_Qt5-5.15.2-py3-none-manylinux2014_x86_64.whl (59.9 MB)
Collecting PyQt5-sip<13,>=12.8
Downloading PyQt5_sip-12.9.0-cp310-cp310-manylinux1_x86_64.whl (351 kB)
|████████████████████████████████| 351 kB 6.8 MB/s
Installing collected packages: PyQt5-sip, PyQt5-Qt5, pyqt5
Successfully installed PyQt5-Qt5-5.15.2 PyQt5-sip-12.9.0 pyqt5-5.15.6
this is the one I have installed
Yeah, could you try using 5.12?
well.. wasn't it working with PySide2 before?
5.15.6 is the newest version of PyQt5 right now... try your code with the updated version of PyQt5 and let us know what happens
you don't need to uninstall PySide2
Maybe if you import PyQt5 before NodeGraphQt they will detect that its been loaded
Traceback (most recent call last):
File "/usr/lib/python3.10/site-packages/NodeGraphQt/widgets/nodes_palette.py", line 50, in paint
painter.drawRoundRect(base_rect,
AttributeError: 'QPainter' object has no attribute 'drawRoundRect'. Did you mean: 'drawRoundedRect'?
``` looks like nodegraphqt doesn't like pyqt5
change the drawRoundRect to drawRoundedRect
I can't, it's a library
yeah
ah, I see
and nodegraphqt uses Qt.Py which should have made it so it's all the same but apparently not
are you using venv? or is PyQt5 installed in your site-packages folder?
site-packages
ha! no wonder you can't get it to work using PyQt: it says very clearly that NodeGraphQt is a node graph framework that can be implemented and re purposed into applications that supports PySide and PySide2.
ah, I see
the first thing they say: https://freesoft.dev/program/101639727
well, guess we can't test on pyqt5
nope, we can't
can you give me a link to your repo and I'll download your code and test it
you'll need to do a pip install in the root folder first
what are the dependencies?
It says it supports PyQt5...
weird
The only place they use that method is in nodes_palette.py
see python_src/requirements.txt
you can try to change it to drawRoundedRect and hope for the best
@rain quarry the requirements.txt file should be put in the root folder of the repo, not in a subfolder (like python_src)
it's because the root contains native code and the entire app is in python_src lol
that's a convention
I'm trying to avoid mixing source roots because that way I can use intellij and pycharm separately without it being a pain in the ass and complaining about the .idea files being used by two IDEs at the same time
it doesn't matter where the actual code of the app is, the requirements.txt file should be put in the root of the repo (besides README.md, and those files)
that's a GitHub convention
just like .gitignore is in the root
please follow GitHub convention
¯_(ツ)_/¯
the dependencies aren't necessary for the native part though, otherwise that'd have a separate requirements.txt
instead of complaining how everything isn't up to your personal preferences you could also just help
Did you try changing the code in that method to drawRoundedRect?
there should be only one requirements.txt file for a project, and it should be placed in the project's root dir
that's a GitHub convention
there's two projects here, that's what I;ve been saying
there's the native code and there's the app
there's no "github" convention
yes, it is
and most projects will have multiple requirements files
I can't, it's in site-packages
You can
ehh, I'd prefer not to edit it
vim isn't the greatest tool for editing large projects
use Sublime Text 😉
could try to patch it then
sublime can't edit root-protected files
what?
It should be in venv/lib/python3.8/site-packages/PyQt5 if you are using a venv
I don't use venvs
what do you mean by root-protected files?
well
