#user-interfaces
1 messages · Page 77 of 1
The basic idea is to create a function that accepts 3 buttons as arguments and set one button to disabled and the other 3 to normal, and then now its all the order you pass in the order of the buttons, like: @orchid stump
def disable_button(b1,b2,b3):
b1.config(state='disabled')
b2.config(state='normal')
b3.config(state='normal')
Since now you need two functions to be executed, you have to specify two functions inside a list, and then those two functions will be executed one after the other
button_A=Button(f0, text='מחזור א', command=lambda:[disable_button(button_A,button_B,button_C),raise_frame(f1)])
button_A.grid(row=0,column=2)
button_B=Button(f0, text='מחזור ב', command=lambda:[disable_button(button_B,button_A,button_C),raise_frame(f2)])
button_B.grid(row=0,column=1)
button_C=Button(f0, text='מחזור ג', command=lambda:[disable_button(button_C,button_B,button_A),raise_frame(f3)])
button_C.grid(row=0,column=0)
No problem 🙂
Recommend you to check https://www.python.org/dev/peps/pep-0008/ and follow it strictly, so you can write better code
I will check it out
@shut pine can you help me with something
yh wassup
Need help are you available
as well as do you have experience with pyqt5
Also here is the problem: I want to stretch a button without having to add it in a layout how can you do that ? using pyqt5 @shut pine
ok thank you
I want to stretch a button without having to add it in a layout how can you do that ? using pyqt5
Try changing its attribute through code
I am creating a frequency table I want to stretch a button but I am encountering a problem first of all I add the button in to a layout and then stretched it but that did seem to work. second I used py QSizePolicy.Expanding that also seemed to not work I have being struggling with this for the past hour I don't know what to do and don't understand what I am doing wrong. I am using pyqt5 also here is the code: py btn = QPushButton(qwidget) btn.setText('Calculate') btn.setGeometry(QtCore.QRect(155, 155,100,30)) btn.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) btn.show() btn.clicked.connect(btn_clicked) qwidget.show()
Can someone here help me please. Why when I type different language into my tkinter entry widget it show question mark(?) ?
probably means the font hyou are using doesnt support the character
what character is it an what font are you using?
the font is something like this https://en.wikipedia.org/wiki/Khmer_(Unicode_block)
Khmer is a Unicode block containing characters for writing the Khmer, or Cambodian, language. For details of the characters, see Khmer alphabet – Unicode.
it my country alphabet
i mean the font you are using in tkinter
for the text where you use these characters, use the font "Khmer UI"
for some reason it still show question mark
uh
import tkinter as tk
root = tk.Tk()text = tk.Text( root, width = 50, height = 20, font = ( 'Khmer UI', 20 ) )
text.grid()
root.mainloop()
Here my code
when I type something like ក it show ? even I though changed the font
i did some testing and this works
tkinter.Label(root, text = 'ក', font=('Khmer',25)).grid(row=0,column=0)
also to find the font, you can just paste the char into microsoft word and it will autoselect font
Is this font pre installed?
I din't have to install it so i think yes
u mean that language ? it existed in window 10 keyboard language
Ummm the font, the font has to be pre installed
ehh how ?
how can i get this effect in adobe or figma
I dont know? Install the font?
Which language are you trying to mimic
I'm sorry but is this related to UI with python
no i'm making it in adobe xd
Yea so how is it a valid question in a python server under a UI channel ?
Agreed, but not related to python
But if someone knows, they can help you for sure 😄
cool
import sys
from PyQt6.QtCore import QDate, QTime, QDateTime, Qt
from PyQt6.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QMainWindow, QMenu
from PyQt6.QtGui import QFont, QIcon, QAction
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
exitAct = QAction(QIcon("exit.png"), 'Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.triggered.connect(QApplication.instance().quit)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAct)
self.setGeometry(300, 300, 350, 250)
self.setWindowTitle('Toolbar')
self.show()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())
if __name__ == '__main__':
main()
Help please, I've decided to learn PyQT to use it for a project a professor gave us, I've been following the instructions here in https://zetcode.com/pyqt6/menustoolbars/. The code works fine but I can't get it to show the icon exit.png, I have the file in the same folder as my python file though. But it's still showing blank.
Menus and toolbars in PyQt6 presents menus,
toolbars, and a statusbar. The examples work with QMainWindow, QAction, QMenu,
and QApplication classes.
by the way this is my exit.png
I tried resizing it to 24x24 since I thought it was because it was so big, but it didn't work anyway. ://
looks like a path problem
is the "exit.png" in the same dir as the python file/project
are u using pyqt ?
There is a program that allow u to build ui work with pyqt ofc all version
yeah Qt Designer, but I wanted to learn it by hand.
damn that a waste of time lol
It may be haha but it would help me a lot to learn manually, since I also need to explain every detail of every line that I added.
u can use that program to learn the code from it when u dont know though so u dont need to ask everyone else
What I just don't get is why it's not showing the Icon.
wait ops
It needs to be an .ico file?
u mean u want it to show on label or icon of the app ?
In here: https://zetcode.com/pyqt6/menustoolbars/#PyQt6-toolbar
I want it to be like this:
Menus and toolbars in PyQt6 presents menus,
toolbars, and a statusbar. The examples work with QMainWindow, QAction, QMenu,
and QApplication classes.
got it I will try to make it work for u
Even though I have both the quit.png and the python file I'm working on in the same folder.
I tried changing it to /quit.png but it didn't work though.
can u give me the full path ?
C:\Users\Administrator\Desktop\College Stuff\1st Year - 2nd Sem\CCC 101 - Computer Programming\Final Project\GitHub
tried moving both files to a different directory just now, still same results.
Tried it on just the desktop. Still nada.
Can we actually use the \ in code?
yes it for dir
Still nada
This is so annoying haha I don't know what I'm doing wrong.
I just copied the code
._.
It worked...
But why though
exit.png should be enough what if I put it in another directory.
I have to submit this aorijgalkje
it some kind of dir thingy it depend on the library how they use it and how they want it to be
hmm yeah I might have to import a library for file handling..
or maybe I'll learn that soon in PyQt6
Thanks!
np
Relative paths have to be relative to where ever the python script is being run from, to find this out, use os.getcwd()
Ohhh I understand now.
C:\Program Files\Python 39
I was using Sublime Text 3 and a custom build system I found on stackoverflow. Seems it's running the python script from here. I Shift+Right Clicked in the same folder as the python file and typed python "UI Testing.py" there and it showed the icon correctly. Neat! Thank you!
hello, I'm looking for help coding my ren'py game,
so basically, the UI of ren'Py game engine is 1920x1080, but my renders/images are widescreen 2560x1080, now I want the images to not auto scale to 1920x1080, instead, maintain the black bars on the top and bottom like how you watch movies shot in widescreen format in VLC player.
I intentionally rendered in widescreen format to give my game a 'film look' but yep, like i said, it always auto scale to 1920 x1080 and it crops so much of the image.
tag me if you have answers, thank you
hello, is there a way to make a dragable widget in tkinter
the user is able to click on it and it gets selected, then follows the users mouse until the user is dragging it and when the user releases his mouse then it s the new position of the widget
Did you know there is a dnd.py, drag and drop, at C:\Users\username\AppData\Local\Programs\Python\Python39\Lib\tkinter that can help you with what you need
Has anyone from here integrated python with ElectronJS? I am wondering whether I’ve picked up something that nobody uses . Just saw a couple projects on GitHub, but honestly the integration looks a bit janky. And unfortunately I am wondering about picking up the project primarily in JavaScript instead because the integration may be too janky with python .
I had not heard of Ren'py so i just looked for documents and it looks like you could use borders to add the black bars:
https://www.renpy.org/doc/html/gui.html#borders
hello, thanks for the reply, I just used the zoom and im.Scale function and it worked
how to change the indicator image (This is tkinter treeview)
indicator?
where is the line thats not working
let me see
Try a png image
what exactly
@opal mulch becuase its ico not png
i changed here to png tho
you have that img?
ofc
Wait I do not think that is how you put images on treeview
oh
i searched on the net
u can put an image when using insert tho?..
can you open logo .png ?
I mean not in the program
yeah
ok
QLabel...
If I am not wrong, you have typed Qlabel it should be QLabel with capital L.
can anyone here me please ?
how to remove title bar from QDialog ?
I know how to remove it from QMainWindow but what about QDialog ?
someone ?
right
and how to make the background TranslucentBackground ?
there a white edge after I know how to remove title from QDialog
nvm I found my own solution here how I fix it:
Dialog.setWindowFlag(Qt.FramelessWindowHint) Dialog.setAttribute(Qt.WA_TranslucentBackground)
anyone know
how to make the font bigger without it being overlapped
by the label
that is text taht looks like weird shapes
if your confsued
Gooday how did u make taht so big
the text
without it overlapping aything
Can someone help me ? I still have problem with remove title. It somehow work if I convert ui file into python file.
But if I were to do like this, it not work
Y Dialog.? Why not self.
It works
have you called root.mainloop()?
Hey, so i am kinda new to Python GUI, and I don't really know what framework and tools I should choose.
I would like to create a GUI with a more modern look, and if possible material design elements.
If anyone has some recommendations or tips I would greatly appreciate it.
I would say to start with the basics, so tkinter, learn the basics like event loop and event driven programming, then move onto advanced frameworks like PyQt and Kivy.
Using PyQt6, is there a way to change the setFixedSize of a QMainWindow after triggering a QMenu action?
i asume so
!paste
https://paste.pythondiscord.com/sasujenofo.rb
I have this code for a Calculator UI, I'm currently trying to make the Menu button Scientific Calculator to work so that I change the fixed size, general layout, and window title of my QMainWindow. What are the necessary steps I need to do? I tried the trigger method but it doesn't seem to be working. Help me please :/
I've also been trying to implement some dialog windows for Contact Us and Documentation, but it's not working ._.
Can someone help me with sizegrip in PyQt please. I have a class like this
import sys
import PyQt5
from PyQt5.uic import loadUi
from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QDialog, QApplication, QSizeGrip
class logscreen(QDialog):
def __init__(self):
super(logscreen, self).__init__()
loadUi("./Qt/logscreen.ui",self)
app = QApplication(sys.argv)
widget=QtWidgets.QStackedWidget()
logscreen=logscreen()
widget.addWidget(logscreen)
widget.setFixedWidth(1280)
widget.setFixedHeight(720)
widget.show()
try:
sys.exit(app.exec_())
except:
print('Exiting')```
and in logscreen.ui have above picture button for resize
anyone help ?
can you tell me, what you want to do in detail ? @verbal storm
can i post my open source github New boiler ui here? (pywebview Frameless with custom handler for resize drag and top bar)
Can someone help me please?
sorry I cant help since I am unable to import the module Calc
I could send in the code for my Calc.
Here's my Calc.py = https://paste.pythondiscord.com/obetijovir.py
wait I know how you can solve your problem
how?
m_SelectCalculator.addAction(self.Scientific_CalculatorAction)``` this will add scientific calculator under the select calculator menu bar as a action then what you can do is ```py
Scientific_Calculator.clicked.connect(self.change_to_Scientific_Calculator)``` this part will initiate the scientific calculator hopefully can you try it out ? @vital sentinel
Ok I will try a different method
can you tell what error it shows it would be really helpful
@vital sentinel
Ok then that's interesting
I can't keep up with all the self inside. I saw that in the Controller class I have to add first self.connectSignals() but when I add it in my Menu class that handles all the Menu Bar stuff it returns an error.
Menu object has no attribute 'connectSignals'
so I thought maybe it's because the self in my Menu class refers to the QMainWindow() object.
So I tried adding an argument MainWindow to the __init__ of my Menu class in an attempt to handle it but nada.
I want that button to resize the app
you can use emit or connect there is no connectsignals function that I know of. try that in stead @vital sentinel
def actions(self):
self.a_ScientificCalculator.clicked.connect(self.change_to_Scientific_Calculator)
self.a_ContactUs.clicked.connect(self.ContactUs)
def change_to_Scientific_Calculator(self):
self.x = QMainWindow()
self.x.setFixedSize(300, 300)
self.x.show()
Wait I found out a different way you can solve this. Can you wait I need to write the code for it
Of course! Thanks for your time.
Scientific_Calculator.triggered.connect(change_to_Scientific_Calculator)``` The function change_to_Scientific_Calculator then does whatever you'd like to have.
that should do the job
Were you able to make it work on your side?
Doesn't seem to do the trick with mine..
def change_to_Scientific_Calculator(self):
self.x = QMainWindow()
self.x.setFixedSize(300, 300)
self.x.show()
Here's my change_to_Scientific_Calculator
you have to put it after the function
self.a_ScientificCalculator.triggered.connect(Menu.change_to_Scientific_Calculator)
self.a_ContactUs.triggered.connect(Menu.ContactUs)
def change_to_Scientific_Calculator(self):
x = QMainWindow()
x.setFixedSize(300, 300)
x.show()
def ContactUs(self):
x = QMainWindow()
x.setFixedSize(300, 300)
x.show()
Decided to change the connect lines to this, but now the created QMainWindow() just instantly closes?
wait I posting a haste bin link with the correct format maybe that should work
Thanks!
to solve this you can do ```py
class MyWindow(QMainWindow):
def init(self):
super(MyWindow,self).init()
self.initUI()
or just wait I will just post the link
can you try running this code hopefully this will work https://paste.pythondiscord.com/uhazijicer.rb
@vital sentinel
Can I just go ahead and change the imports to PyQt6? Since that's what I'm using?
Oh sorry for the indentation errrors
https://paste.pythondiscord.com/ajubunerus.rb
Changed the indentations and tried to fix some of the errors.
But same issue, it's closing immediately after it opens.
does it give an error
try remove class main window that should do it
try removing this part
@vital sentinel
which line there?
from line 6 to 9
d
Does anybody know of an embeddable world map (preferably offline) module for GUI development? I'd like to change the displayed location programmatically based on coordinates.
Could anybody offer advice and suggestions about my first big python project?
https://github.com/Sn4u/met-eireann-status/tree/master
Looks pretty good. It would be nice to provide install instructions if you want feedback.
you should be able to just download the project and run met_eireann_status.py. running randomise_demo.py beforehand will make sure that the demo warnings are not expired and will show up
explain this in the readme and add a requirements.txt file
👍
OK I want to move the button on top of the table widget. I have tried move and set geometry they both don't seem to work so what should I do. Here is the code for the button: py layout = QVBoxLayout() btn = QPushButton(qwidget) btn.setText('Calculate') layout.addWidget(btn) btn.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) btn.show() btn.clicked.connect(btn_clicked) qwidget.show() the tablewidget and the button are added in the same layout also I am using pyqt5
With on Top do you mean
</Button>
</Table>
Or
<Table> </Button> <Table>
The former should be the default when adding the button to the layout before adding the table
If you want the latter you can use setCellWidget
@fading basin
I mean the 1st one
class AWindow(QMainWindow):
def __init__(self):
first = QLabel("Toaster")
second = QLabel("Lorem Ipsum")
self.layout = QVBoxLayout()
self.layout.addWidget(first)
self.layout.addWidget(second)
This will display the widgets in the correct order
Using a button and a table should not make a difference
Also I dont get Why you are calling .show on the button widget
just call .show() only on the window.
hii. I will make an interface using python tkinter. I'm doing this for the drone. A total of 5 data will be displayed on the screen. can anyone help me? Or someone experienced in these matters?
like this
thank you for your assistance its really appreciated 😊
@wooden imp
i said kivymd not kivy
kivymd is just styled kivy
Trying to be modern? Wont work easily, use PyQt or Kivy
or kivy really - especially if you arent constrained to tkinter
wouldn't tkinter?
and i have no idea about gui. My specialty is image processing. I have to do this interface in 1 week. Can you help me with the software?
tkinter is not modern GUI toolkit, more like a native windows 7 app
well there multiple things going on there. is that just for display or is there some inputs to be taken. either way looking at Image widgets and then adding the data interpretation dials.
I think you forgot to reply to some message, or are you just casually talking
Just more casually to EFE's ping - this channel's traffic is relatively low.
I probably could throw something together; but the math for the visualisation depends on the input data...
Ok is there a way to add Qlabel into QLineEdit
How can I flip this picture according to the movement of the drone? I couldn't write the code. can someone help me? using tkinter.
here's a suggestion you can use PIL and import image then using that you can rotate the image example```py
from PIL import Image
image = Image.open('Audi.jpg')
rotate 270 degrees counter-clockwise
imRotate = image.rotate(270)
filename = "AudiRotated2.jpg"
imRotate.save(filename)
a simple way to show the image file is to use module webbrowser
which activates the default viewer associated with the image
works with Windows and Linux
import webbrowser
webbrowser.open(filename)```
I know that. What I want to do is to be constantly changing. so it will change in real time
Ok then I being writing the code for it
and ı use tkinter for interface
I'm sending a code from dm. I want to add your codes to the interface I made
Are you looking for placeholder?
Sure you can make use of root.after(). How do you get the degree of rotation
I will get the data from the drone. will constantly change
I need to make an interface. Can someone send me a message to help me?
It wont be so hard, you can do it yourself following the documentation.
Can we add a specific location on the map to the interface with tkinter? How it is made?
map? location? which? You mean using maps with tkinter?
Everything you actually need is readily available with PyQt but it is not that easy to understand for beginners
I will follow the drone on the map. so i need a map that will be constantly updated
Are you a beginner?
I know python. but the interface is for the first time
how can I do it. no information found on the internet?
How do I get latitude and longitude from user and show this location on map in pyqt5 widget?
My OS is Windows, and I found out this link:
https://github.com/eyllanesc/qMap
But when run, this error
this pyqt5
i want with tkinter
this code not working ??
or i dont using?
@tawdry mulch
How can I add an image to the canvas?
Bro all these are basics, you can just type into google
If you want to show map in the GUI, use PyQt
With tkinter there is no way to show map
Unless there is an API that will get the coordinates and then return the images, with which you can update your GUI, but not efficient
Which Qt widget is best used for a duration?
but im unsure how to configure it to work with timedeltas
What are you trying to do
User see timedelta
user edit timedelta
me use timedelta to do physics
now I dont need much accuracy, I expect values of up to 5 hours. I would like to have use widgets with differing accuracy - one that uses seconds and ms and one that is only hours and minutes.
Basically I look to create a TimeEdit that takes in hh:mm but could theoretically have 99h in there and a time edit with hh:mm:ss:mss
Of course I do want to limit the minutes to 60
(similar with seconds)
Hello, I have a component im tryuing to make with a Qframe, and im thse little widgets withing it have their own styles like teh icon button needs to be round and everything, but when i aling it with a grid layout, they become squares and the styles are overrided, how do i keep the styles on? or is there antoehr way to center these widgets
the backgroundi sblue to show you the size of them
PyQt5/PySide question: I want a widget to be a square - as big as fits. More generally, fix the aspect ratio and expand it as much as possible. To be specific, at this point this widget (a QOpenGLWidget) is a central widget inside a QMainWindow, with two panels fixed at the sides. Lots of (mainly old) answers on SO, but none of them actually seem to work.
Are the two "panels" dockwidgets or just layout on each side of the main layout of the main widget where the QOpenGLWidget is. As you can see, kind of hard to understand. Can you share your code?
how are you subclassing the widgets?
any ideas why my counter is -1 behind in the gui compared to terminal? code here: https://paste.ofcode.org/sieCLszyiyDViZz3b3qNFy pyqt5
Yeah, dock widgets
I do something like
self.dockRight = QDockWidget('parameters', self)
self.dockRight.setAllowedAreas(Qt.RightDockWidgetArea)
self.dockRight.setFeatures(QDockWidget.NoDockWidgetFeatures)
self.dockRight.setMinimumWidth(200)
self.dockRight.setMaximumWidth(600)
self.addDockWidget(Qt.RightDockWidgetArea, self.dockRight)
and likewise for the left hand side dock
if you set the QOpenGLWidget as the centralwidget, it doesn't resize or what's the problem
like I said, it won't keep a fixed aspect ratio
The only workaround that actually worked for me was fixing the size of the central widget
But I want it to expand if the window size allows it to
are you setting the centralwidget as a QWidget with a layout or directly adding the QOpenGLWidget
I'm setting it with window.setCentralWidget(myWidget)
but that doesn't really matter, I tried various layouts and other solutions, and would happily change to a different scheme, unfortunately none of them work
BTW I happen to think the whole widescreen fad is plain stupid. 4:3 was pretty much a perfect formfactor, though myself I wouldn't mind a square screen. But that's a totally different discussion.
I mean, let the folks who use their computers mainly for watching movies have their widescreens, but for actual work different formfactors would be more suited, while the market gives you no choice whatsoever.
hi I am using recursion and turtle graphics to create a fractal art.It is working fine but the levels (a var) is 2 then after the recursive funtions call it is 1 .I dont know why please
before the first call of the function the levels are 2👇
can some one help me? With .py to .exe
after the first call it is 1
👇
hi I am using recursion and turtle graphics to create a fractal art.It is working fine but the levels (a var) is 2 then after the recursive funtions call it is 1 .I dont know why please help.please be brief.Thank you
sure
yea I have no clue 😔
can anyone help me ? please 😦 #help-pineapple
you mean, you wouldn't know how to start setting up a widget to be resizable while preserving aspect ratio?
i mean QSizePolicy should work with resizing, but I don't know about your aspect ratio issue
QSizePolicy is no help here
maybe try overriding the resize method
I'm tryna help you here, but I've never encountered this issue
okay
sorry
dang this chat is dead
can someone help me with blessed (or curses if i need to switch) in #help-burrito
not if u scream for help(SOS)
I wanna scream but I might get banned so...
I want my calculator to play a sound whenever I press a button, and also a looping background sound. Is there a way I can do this?
Using PyQt6
Well, just save ure sounds as files (mp3 for ex) and use playsound :
Lets supose u have a background sound called main.mp3 and another one called button.mp3 that need to be called once when u press the button :
Using threading that might do that :
from threading import Thread
from playsound import playsound
def TheFunctionThatWillBeCalledWhenUWillPressAButton():
playsound("button.mp3")
def background():
while True: #I was not going to write while 1, that false
playsound("main.mp3")
Thread(target=background, daemon=True).start()```
Then just define that when u press the button it will call the first function, and ure 👌
@vital sentinel u asked for tag xD
Are those imports prebuilt with python?
Oh okay looks like I only need to pip install playsound
Where do I put these lines just to be sure? I added the playsound and background functions to my controller class which handles the button presses, where do I put the last line?
It doesn't seem to work..
@zealous gorge
oh wait it worked, forgot the playsound(self)
I can't seem to get the background music to work though
My button has two connects each click, one for the playsound and one for the QLineEdit (button click adds the text of button to a QLineEdit). But there's a delay when the sound is played and the text is added to the QLineEdit. Any remedies?
Judt add the playsound("button.mp3") at the function called when u press the button and the other finction can be set wher u want (dont forget to add the Thread(target... to ure main program/function
hey smart python people...
so, im making a tkinter application for some reason im getting a "referenced before assignment" error when the variable was already declared and even used by another function by the time i used it in another...
heres the code:
count = 0
def packData():
#Obtain target data (get the meeting that has the index of count, i have to do this cuz i meetings is a dictionary)
targetMeeting = ''
identifierCount = 0
for meeting in meetings:
if identifierCount == count:
targetMeeting = meeting
identifierCount += 1
#Make labels with data (commented out this part so its not distracting)
#meetingNumberLabel = tk.Label(frame, text='Meeting Number: {}'.format(count), bg="white")
#meetingNameLabel = tk.Label(frame, text="Name: {}".format(targetMeeting), bg="white")
#meetingIDLabel = tk.Label(frame, text="ID: {}".format(meetings[targetMeeting]['id']), bg="white")
#meetingPwdLabel = tk.Label(frame, text="Password: {}".format(meetings[targetMeeting]['pwd']), bg="white")
#meetingLinkLabel = tk.Label(frame, text="Link: {}".format(meetings[targetMeeting]['link']), bg="white")
#Pack labels
#meetingNumberLabel.pack()
#meetingNameLabel.pack()
#meetingIDLabel.pack()
#meetingPwdLabel.pack()
#meetingLinkLabel.pack()
packData()
def moveToNextMeeting():
count = count + 1 #this is where the error arises
for widget in frame.winfo_children():
widget.destroy()
packData()
nextMeeting = tk.Button(root, text="Next Meeting", padx=10, pady=5, bg="#263D42", command=moveToNextMeeting)
nextMeeting.pack()
root.mainloop()
i dont understand why the error arises when count is already declared... can someone please help?
please tell me if im doing anything wrong, im new to python programming..
Maybe add global count to each of your functions.
count = 0
def packData():
global count
...
def moveToNextMeeting():
global count
...
@olive cove
what does that do? @vital sentinel
It makes it so that you're always using the count variable that is outside the functions.
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
it says 'name 'count' is not defined'
Traceback (most recent call last):
File "main.py", line 201, in <module>
mainRun()
File "main.py", line 194, in mainRun
viewMeetingsGUI()
File "main.py", line 164, in viewMeetingsGUI
packData()
File "main.py", line 146, in packData
if identifierCount == count:
NameError: name 'count' is not defined
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
!len
Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.
for i in range(len(my_list)):
do_something(my_list[i])
The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.
!pyautogui
why doesnt it work @vital sentinel ?
Hello guys I am trying to make a text-to-speech app using python and I want to add text highlighting functionalities like this ( https://www.youtube.com/watch?v=lTYWGWRoYNA&t=219s ) any ideas how can I accomplish this in python
Essay series 1 - Essay 2 - Compensation - Ralph Waldo Emerson
All things are double, one against another.
Tit for tat; an eye for an eye;
a tooth for a tooth;
blood for blood;
measure for measure;
love for love.—
Give and it shall be given you.—
He that watereth shall be watered himself.—
What will you have? quoth God; pay for it and take it...
lmao
No offense, but that's a horrible approach. You want to use the native PyQt6 libraries with something like
self.player = qtmm.QSoundEffect()
self.player.setSource(qtc.QUrl.fromLocalFile(sfx_file))
self.btn.clicked.connect(self.player.play)
where the import is as such
from PyQt6 import QtMultimedia as qtmm
There are many other implementations and some for background music as well. Do some research and you'll have a great app.
working in qt5. Have an embedded pyplot as the GUIs main widget. Wanted to replace the canvas with a new pyplot upon some event. Works fine, replaces the old pyplot with new. But using the same commands to try and replace the new canvas with the old it wont execute. Any thoughts as to why?
self.spectrum = Figure()
self.canvas = FigureCanvasQTAgg(self.spectrum)
plot_layout.addWidget(self.canvas,stretch=5)
#replace canvas with new mpl
self.fig=plt.figure(figsize=(12,8))
parent.plot_layout.removeWidget(parent.canvas)
parent.plot_layout.insertWidget(1,self.fig.canvas)
#when finished with function, replace canvas to initial canvas
self.parent.plot_layout.removeWidget(self.fig.canvas)
self.parent.plot_layout.insertWidget(1,self.parent.canvas)
the only difference as I can see is Using the FigureCanvasQTagg in the initial and just using self.fig.canvas in the replacement. Dont think thatd have anything to do with it though?
nevermind! just had to close out the canvas as well as removing the widget. I'm a dummy
can you give an example code
You could use winfo_children() to get a list of child widgets and then destroy the widgets that are instances of tk.button isinstance(widget, tk.Button)
The following creates 5 widgets randomly picking a label or a button, clicking the last button will destroy all buttons.
import tkinter as tk
import random
class TkApp(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for index in range(5):
widget_choice = random.choice((tk.Label, tk.Button))
widget = widget_choice(self, text=f'Widget{index}')
widget.pack(padx=5, pady=5)
self.button = tk.Button(
self, text='Destroy buttons', command=self.on_button)
self.button.pack(pady=5)
def on_button(self):
for widget in self.winfo_children():
if isinstance(widget, tk.Button):
widget.destroy()
if __name__ == '__main__':
app = TkApp()
app.mainloop()```
I'm getting an Import Error when I try to import QtMultimedia.
I did it the same as you.
ImportError: cannot import name 'QtMultimedia' from 'PyQt6'
Does anybody have any style sheet for PyQt lying around? Or can anybody guide me on making my calculator look nicer please.
:incoming_envelope: :ok_hand: applied mute to @vital sentinel until 2021-07-02 04:22 (9 minutes and 59 seconds) (reason: newlines rule: sent 113 newlines in 10s).
!unmute 311172428049022978
:incoming_envelope: :ok_hand: pardoned infraction mute for @vital sentinel.
!paste @vital sentinel use this
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/egedeloliy.css Here is my qss file.
I want the buttons to actually look like buttons, and the QlineEdit to be sort of like sunken. I also tried changing the font family of the buttons' text but it broke the design, and font-style: bold; won't work too.
Kind of like this. The buttons look raised and the QLineEdit sunken. QSS is kind of a challenge for me.
mb, apparently it does not work the same in PyQt6 as in PyQt5. https://www.qt.io/blog/add-on-support-in-qt-6.0-and-beyond
I want to rotate an image in tkinter. how can I do it?
Hey guys how do i place text in the center with the grid() in Tkinter I just started learning so please help
how do i use padx in pack() funcion in Tkinter
Does pack(padx=10) not work?
I do not undestand, text will be centered by default, what do you mean centrered
yeah i figured it out but thanks
any other package i could use to make ui, other than tkinter and pyqtinsert_num
i learned about PySimpleGUI yesterday. It is a lot simpler than tkinter and pyqt
so I developed a program in jupyter notebook and its completely stable, never get any errors. My professors runs everything through command line and he noticed if he runs in jupyter, its still stable, but if running from command line...especially when he exits (occasionally elsewhere) he gets a segmentation fault.
Anyone know why this may be?
My first thought is if it's threaded a race condition, but if you're in a notebook I doubt it'd be that
threaded race condition? Whats that?
Well the issue arises from command line usage. Running in jupyter is fine
Its jus simple
I have a QMainWindow with a QMenu - QActions that opens another QMainWindow. What I want to happen is while the other QMainWindow is opened, the parent (first) QMainWindow can't be clicked on, if the user tries to it brings up focuses on the child (other) QMainWindow. What can I do?
Using PyQt6.
Help :<
I will make a cockpit interface. Which library do you think I should use? (I know intermediate python)
Use the kivy or pyqt
thanks a lot! This really helped me a lot!
So, i want to change the background of the scrollbar in tkinter from white to a grey tone. bg, activebackground and troughcolor, etc didnt work. Can someone help?
Its the first time for me working with scrollbars, thats why
I am on windows btw
How do I make a label which tells the amount of CPS, the label I made doesn't see mto update.
or
from tkinter import *
window = Tk()
window.geometry("350x350")
window.config(bg='black')
clicks = 0
def click(event):
global clicks
clicks += 1
print(clicks)
def reset(event):
global clicks
clicks = 0
print("Your clicks are now: " + str(clicks))
window.bind('<Button-1>', click)
window.bind('<Button-2>', reset)
canvas = Canvas(window)
Label(text='CPS Test', font=('Tahoma', 20), bg='black', fg='gray').pack()
Label(text='Check the terminal for your CPS ', font=('Tahoma', 15), bg='black', fg='gray').pack()
cpsLabel = Label(text='CPS: ' + str(clicks), fg='gray', bg='black', font=('Tahoma', 18)).pack()
window.mainloop()
Will it be qt creator?
and what is your question?
how do i center it
There is an argument in widgets 'justify' so you can pass justify='center' and it will center the text
It is not advisable to use **from tkinter import *** see https://python-forum.io/thread-4.html
Your label widgets should have their parent as the first passed in attribute.
Your event handlers are altering the clicks attribute value but the label itself has not had it text value updated.
Rather than using global use a class to group related attributes and methods together.
The following is an example of your code that does not use * import or global, it uses a class and has a method to update the label that is called in the event handler methods that alter the value of clicks.
import tkinter as tk
class TkApp(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.geometry("350x350")
self.config(bg='black')
self.clicks = 0
tk.Label(self, text='CPS Test', font=(
'Tahoma', 20), bg='black', fg='gray').pack()
tk.Label(self, text='Check the terminal for your CPS ',
font=('Tahoma', 15), bg='black', fg='gray').pack()
self.cps_label = tk.Label(
self, fg='gray', bg='black', font=('Tahoma', 18))
self.cps_label.pack()
self.update_cps_label()
self.bind('<Button-1>', self.on_button1)
self.bind('<Button-2>', self.on_button2)
def update_cps_label(self):
self.cps_label.config(text=f'CPS: {self.clicks}')
def on_button1(self, event):
self.clicks += 1
self.update_cps_label()
def on_button2(self, event):
self.clicks = 0
self.update_cps_label()
if __name__ == '__main__':
app = TkApp()
app.mainloop()```
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
hey does anyone know of a UI library that doesn't have strict threading requirements? basically, I want to be able to run a Python script in my game and a UI window pops up. then I want to be able to close the window, and run the script again, and have it pop up again. my best understanding is that PyQt and wxwidgets are entirely incompatible with this use case. any ideas?
(so to be clear, both runs would be in the same python shell -- no avoiding this unfortunately)
or would it be out of the realm of sanity to multiprocess for this??
last issue in my program is just difference in how a directory in inputted for saving. For windows I have to use \ to identify a directory. For mac or linux i think its '/'
Any way to prepopulate a save folder directory or something with whatever usage is for that OS?
i think pathlib can do this
huh...I cant get a double backslash to work
thanks booing. I have no idea on your problem haha, sorry mate
>>> Path('.').absolute()
WindowsPath('C:/Users/booing')
blessed vs curses?
how do I remove the padding/built in margin surrounding my hello world label in the window, in PyQT5?
found the solution, layout.setContentsMargins(0, 0, 0, 0) around any layouts used
Hello, I am using PyQt5 to create a gui, defining a buttons class in a separate .py file and importing it, then trying to use a method from my buttons class to change the color of a label in my Ui_MainWindow
like so:
class buttons(object):
def __init__(self, Ui_MainWindow):
print('creating buttons object')
def func(self):
Ui_MainWindow.label.setStyleSheet("background-color: green;")
This is throwing an error
Traceback (most recent call last):
File "c:\Users\Gaming\Google Drive\Code\Python\help\main.py", line 13, in <lambda>
self.pushButton = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.btn_obj.func())
AttributeError: 'Ui_MainWindow' object has no attribute 'btn_obj'
I have isolated the code from a bigger project into smaller code and am happy to share with anyone who would like to see.
If I understand correctly, since the label is an attribute of a Ui_MainWindow object, and not the class itself it is unable to be changed in the way that I am doing it. I am hoping someone could show/tell me the proper way to implement this sort of thing.
if anyone has experience with python prompt toolkit can I get some help in #help-chestnut
@vital sentinel u can just disable the mainwindow and enable it on wheh u close the child
@analog flicker are u using Qt designer generated code or the UI is written by u
@upbeat island use a stylesheet or check for the padding of the parent widget by my Knowledge its the padding of the main Widget
@onyx spoke u should use QML its way easier by my knoweledge and u can use the Qt design studio Standalone
Hey
So this my UI
new_project = Button(text='+',
font_size='100sp',
background_color=[0.4, 0.4, 0.4, 0.7],
size_hint_x=None, width=215,
size_hint_y=None, height=215)
text1 = Label(text='Create New Project',
font_size='20sp',
size_hint_x=None, width=215,
size_hint_y=None, height=30)
this is my button and label code
how do i make it
not stick to the corner
and just have a bit of a gap
It is designer generated. I solved it though but thank you very much for reaching out!
u subclass the designer generated code. like
class UI_main(Ui_mainwindwo, QTWidget.MainWindow): super().__init__(); self.SetupUi(self)
I actually have a new issue I am dealing with in PyQt5 now.
I am using UI code generated by QT Designer and I am trying to
use self.setWindowFlags but am getting the error
AttributeError: 'Ui_MainWindow' object has no attribute 'setWindowFlags'
The code I added is to try to set the flags is :
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.WindowStaysOnTopHint
)
oh sorry im just bad at tkinter
@analog flicker u need to subcalss it with the code i gave u to create a mainwindow to actually hold the UI
Alright let me try, but I am a beginner so I may have to ask for further guidance. I will try on my own first though. Thank you again.
class PlayerUI_obj(PlayerUI, QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
```@analog flicker
@worthy ridge I added like this:
class PlayerUI_obj(Ui_MainWindow, QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.WindowStaysOnTopHint
)
now do I need to add PlayerUI_obj to the code here?:
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
class PlayerUI_obj(Ui_MainWindow, QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.WindowStaysOnTopHint
)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = PlayerUI_obj()
ui.show()
sys.exit(app.exec_())
It works perfectly! Thanks for all your help today @worthy ridge.
As I am sure you can tell I am a noob programmer. I watched a video series on PyQt5 to try and learn it but do you have any recommended reading material or youtube channels so that I can further my understanding of it?
tbh i never used any resource so i cant suggest i just go refer the docs when im stuck its fast
Alright, well thanks again. Have a great day 🙂
How do I achieve that?
Hello! What is a good lib that could help in viewing charts ( pie charts ) in pyqt5?
Tried using pyqtcharts but couldn’t find docs for it
Why does this work
class MainWindow(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout(self)
label = QLabel()
label.setText("test")
layout.addWidget(label)
self.setLayout(layout)
self.showMaximized()
but not this?
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
layout = QVBoxLayout(self)
label = QLabel()
label.setText("test")
layout.addWidget(label)
self.setLayout(layout)
self.showMaximized()
if I use QMainWindow instead of QWidget then the layout stops working completely, and nothing shows up on the window
You must be having MainWindow.show running at the end of your code. i.e., w = MainWindow()
w.showMaximized()
You can only use it once
yeah I have show() in
def main():
app = QApplication(sys.argv)
main_window = MainWindow.MainWindow()
main_window.show()
sys.exit(app.exec_())
Remove it or remove the self.showMaximized from the MainWindow class. It should work
doesn't make a difference, subclassing MainWindow from QWidget works, but subclassing it from QMainWindow doesn't
ah I think I know why, QMainWindow requires that you have a central widget, so you can't have layouts in it, if I understand it right
what is the way to pack python installation into standalone installer with all its dependencies for windows?
I'd like to know this too
Don't think this is the right channel tho
windows installers are user interface
ig
found this
Wish I had researched a bit before started working on Tkinter but would anyone recommend using tkinter.dnd module or its equivalent workaround from StackOverflow or should I use a different GUI tool?
What?
Sorry I wasn't clear. I was talking about Drag and Drop functionality. Is this available somewhere in tkinter (hopefully built-in) or should I use a different GUI tool thats easier for drag and drop?
dnd is built in right? Use it or use PyQt.
how would i get the number of widgets in a row(grid layout) kivy
it is very much possible
but it defo wont be built in
as for a better GUI tool
im using kivy, but its harder than doing it with tkinter 😅
i dont think any lib support dnd actually
you can try QT, but i doubt it, easiest to just implement it yourself with tkinter
@meager niche u can inegreate matplotlib in Qt
widget.setEnabled(true) or false add this to the closeevent of the child
@upbeat island mainwindow < centeral widget < child and child widgets, this the hirarchy that muct be followed to make a GUI work and frames to show up properly
Qt has that inbuilt just u will need to set the flag for that widget
i am using kivymd how do you extract text from confirmation dialog box suppose in the below example
https://kivymd.readthedocs.io/en/latest/components/dialog/#kivymd.uix.dialog.MDDialog.content_cls
@worthy ridge
i dont do kivy
thx for looking
hi
idk if im on the right chan but im looking a help about spyder
just wondering if someone did have a problem with kernel
Hi, I'm using tkinter for my frontend project, in my case each interface is a class, I have a problem in one interface who uses a normal class (not tkinter class) that class is just processing. I'm not an expert in OOP, let me explain you more about my issues and what I want to do.
My goals are: I have an "Import button" I imports a video, from the path of the video, I would make some processes, I have a class "process" the are different methods in that class, the class "process" have 1 attribute 'path of the video', the second class is "Gui" a simple interface that got 2 buttons "import" and "process", the importation method is in Gui class, so how can I do to declare and return the path of an imported video.
What I've done for my part I just declared a variable out of the class Gui, and call it in the importation methods but i don't works.
Thank you.
is there a question in all that I missed?
what is code
Yes, the question is how can I do to declare and return the path of an imported video
Are there any good guides for making modern looking UI in python? The ones I found look very 1990s..
using return.
No, it not works
Then show your code please. @noble star
i'm making a tkinter application and i'm trying to extend functionality for an Entry to show some default text if the Entry is empty. For some reason the binds on the FocusIn and FocusOut causes the application to crash, but I don't know why. It works fine if there is 1 of these objects, but I use 4 (happens whether I have a textvariable or not, so I'm unsure if this has anything to do with it)
class LabeledEntry(tk.Entry):
def __init__(self, parent, default, *args, **kwargs):
tk.Entry.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.default = default
self.lose_focus()
self.bind('<FocusIn>', self.get_focus) # crashes on click from this
self.bind('<FocusOut>', self.lose_focus)
def get_focus(self, event=None):
if self.get() == self.default:
self.delete(0, tk.END)
self.config(fg="black")
def lose_focus(self, event=None):
if self.get() == "":
self.insert(0, self.default)
self.config(fg="gray")
i'd found the code off of a reddit post:
https://www.reddit.com/r/learnpython/comments/6tw5ve/tkinter_entry_box_how_to_declare_a_light_grey/
didn't seem like what I'd typed in was too far off from what was posted
2 votes and 2 comments so far on Reddit
Give the entire code, not reproducible so far.
i'm using it in another class:
class Block(tk.Frame):
def __init__(self, parent, version, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.version = version
self.locked = tk.PhotoImage(file="img/lockClose.png")
self.unlocked = tk.PhotoImage(file="img/lockOpen.png")
self.columnconfigure(0, weight=3)
self.rowconfigure(2, weight=3)
self.checked = tk.BooleanVar()
self.normal_checked = tk.BooleanVar()
self.toggle = tk.Checkbutton(self, text=version, variable=self.checked, command=lambda: test(version))
self.toggle.grid(row=0, column=0, sticky="W")
self.lock = tk.BooleanVar()
self.lock_toggle = tk.Checkbutton(self, variable=self.lock, image=self.unlocked, selectimage=self.unlocked)
self.lock_toggle.grid(row=0, column=1, sticky="E")
self.filter = tk.StringVar()
self.filter_box = LabeledEntry(self, "Filter Files...", text="Filter Files...", textvariable=self.filter) #<-- the Entry in use
self.filter_box.grid(row=1, column=0, columnspan=2, sticky="EW")
self.listbox = tk.Listbox(self)
self.listbox.grid(row=2, column=0, columnspan=2, sticky="NSEW")
which gets instanced multiple times within a NoteBook.
So the app just crashes?
when i click the entry it just freezes
without the binds the entry works fine, with the binds the moment i interact with it directly it crashes
What about without the textvariable.
same problem, strangely enough the second visible Entry starts with black text instead of gray text
Ok where else are you using self.parent, within LabeledEntry.
that's the whole LabeledEntry code
Okay a wild try: replace all self.parent with self.master and try again
self.master = parent?
Yup
seems to do the same thing
Okay let me see
Yep, like I predicted the issue was self.parent itself.
actually - now that you mention it, i did put self.master there as I didn't know that was a thing, i guess that's what was messing it up?
See I confused myself 😛 Which was originally there, self.parent or self.master at line 51
it was originally self.master, if i change the name it works fine
thanks for the help, i shoulda caught on when you said self.master but i forgot i set that lol
Okay yes, I was wrong but I had the correct idea. Do you want to know the explanation?
yeah, what is the difference with parent and master?
It is just that self.master is used by tkinter widgets inside their class, so when you use self.master, you are changing what was defined before, and should be a window, changing it to a Frame causes the error.
Avoid using self.master at all, stick with self.parent or self.root, better
oh, so it was essentially pointing everything to the same thing. ouch. makes sense.
i should read more about the class before i trip over the built in variables too much. i keep getting nasty surprises all the time
Well if you check __init__.py inside tkinter folder, you can see in line 2258 that self.master = master is set, and this is for the class BaseWidget and as far as I know, all widgets indirectly/directly inherits from that class, making self.master part of your namespace(I guess) too, and when you change it, BaseWidget fails and all child classes also start to fail.
wanderson
anyone here know QFileSystemModel and Qtreeview ?
I already write the code to list all the file in dir and it look sth like this
but I want to add the feature where I can search and fliter the files inside the dir
is there anyway ?
The code look something like this:
path = "subjects"
self.model = QtWidgets.QFileSystemModel()
self.model.setRootPath((QtCore.QDir.rootPath()))
self.treeView.setModel(self.model)
self.treeView.setRootIndex(self.model.index(os.path.join(dir, path)))
self.treeView.setSortingEnabled(True)
self.treeView.doubleClicked.connect(self.open_file)
def context_menu(self):
menu = QtWidgets.QMenu()
open = menu.addAction("Open")
open.triggered.connect(self.open_file)
cursor = QtGui.QCursor()
menu.exec_(cursor.pos())
def open_file(self):
index = self.treeView.currentIndex()
file_path = self.model.filePath(index)
os.startfile(file_path)
dir = os.path.dirname(__file__)```
My project stuck here please help me
that i wont think is really related to the GUI, you can create a function that does it and re populate the widget based on it
i have a custom File system model that uses checkboxes u can loook into to the code if u wana mess with the underlying model
https://github.com/UGLYclown999/Apollo/blob/3f24d3d61f89b181de74f69ce51beb5bcbff2be8/apollo/app/misc_app/file_explorer.py#L8
apollo/app/misc_app/file_explorer.py line 8
class CheckableFileSystemModel(QtWidgets.QFileSystemModel): # Untested```
FS queries are expensive so repopulating is difficult as Qt file system load the data in chunks so u cant query the full tree and repop
thank you for your help I will check out your code.
I also found other script too that work but It seem like I dont understand it.
@worthy ridge
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
le = QtWidgets.QLineEdit(textChanged=self.on_textChanged)
self.lv = QtWidgets.QListView()
self._dirpath = QtCore.QDir.homePath()
self.file_model = QtWidgets.QFileSystemModel()
self.file_model.setRootPath(QtCore.QDir.rootPath())
self.file_model.setFilter(QtCore.QDir.NoDotAndDotDot
| QtCore.QDir.AllEntries
| QtCore.QDir.Dirs
| QtCore.QDir.Files)
self.proxy_model = QtCore.QSortFilterProxyModel(
recursiveFilteringEnabled=True,
filterRole=QtWidgets.QFileSystemModel.FileNameRole)
self.proxy_model.setSourceModel(self.file_model)
self.lv.setModel(self.proxy_model)
self.adjust_root_index()
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(le)
lay.addWidget(self.lv)
@QtCore.pyqtSlot(str)
def on_textChanged(self, text):
self.proxy_model.setFilterWildcard("*{}*".format(text))
self.adjust_root_index()
def adjust_root_index(self):
root_index = self.file_model.index(self._dirpath)
proxy_index = self.proxy_model.mapFromSource(root_index)
self.lv.setRootIndex(proxy_index)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())```
if can. could u help me read that code and copy paste to your note and put # above the method to explain me what it does.
which one is better : tkinter, kivy or PyQT5 ??
pyqt is good cuz it have their own designer
is this the gui channel?
yea but this channel not much out of help
ight thanks
What does that mean
Dont query from the tree, query from the directory chosen?
ehh I don't understand can u like show the solution in code please. I'm kinda new to it
no the other way around add a filter to the tree and only filter out the content that is being displayed
that good too. since I just making it easy to sort my school subjects pdf file and I dont really make sub folder
i always suggest Qt
PyQT is for native look
hmmhmm? It has style sheet
nope lol
it does have style sheet
@noble star https://github.com/UGLYclown999/Apollo i use it extensively
Well i dont know much about PyQt, but if I were to make something with tkinter, I would do like that
@noble star https://github.com/nihaalnz/PassLost no preview but feel free to download the app from releases
its easy to hide rows than to repop the full table
atlast can someone educate me this script please ?
file sys model > filter proxy > view u query the proxy to just show valid data
like filter is a mask that u use to hide stuff ur not using techinically
file sys model > filter proxy > view data flow diag
ok ok I got some glimpse of it thank for the hints
I run into another problem when I switch from Qlistveiw to Qtreviewer even though I set the path dir to other location. it always show only root dir path
Hello. Im trying to make a scrollable frame, but Im not quite sure how a scrollbar works, and I kinda need some help understanding it.
I mean how do I make a scrollable canvas?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
is there a way i can make my gui show if one of the buttons is on or off for example like auto fish: On
so many passed functions rip
show what happens when u run it
changing the buttons background color?
Ah
you can change the button text yes
Nice
oh lol made that before
wait wait
wait a fucking minute
thats against ToS

is it?
it very much is
anyways
since its the gui
ill help
:3
dont tell anyone
huh
but just the gui.
background color/changing the text of the button
when was it againced the tos
It is.
You cant bot farm
hmm looks like im making a gui forsomething else
after you teach me this lmfao
also you cant automate your account with-
lol
ahh
i cic
😉
lol i aint tryna get banned
mhm
anyways
yeah
i recommend changing background colour
ok to what?
sadly I can't run stuff overnight cause it's 48°C yes very nice
of the button
white
green/red?
of the button
yes.
btn.config["text"] = "blah"
thats not
idk that's whats in my head
niceu
like 2 years ago lol
so is it possible to say if its on or off
now use requests to make the functionality
yeah
when u click
make it black
when you click
if u click it just toggle it using a book
make it not black, ie, white
ok i started python yesterday i have not gone that far
bool*
bool
people nowdays
start python
lol
and start making guis
i know a little c++
but thats it...
I started with b a t c h
you want me to make a booliant?
it took me 6 months to learn the fundamentals :/
and as for python beginner level, took me a year, that is, what i consider beginner
now id say im intermediate
and I made an a n t i v i r u s in batch
.. ..
want me to get rid of all of the def funtions?
intermediate != pro
kk
import code
so i made a boolian
according to me,
intermediate is when you are advanced at a certain field, and you are intermediate at the pro lang you use for it
advanced is when you are good with all the concepts in that pro lang, for example meta classes and itertools in python, and 400 other things
everytime u click the button, do bool = not bool
mhm
to reverse the value
then after u reverse it, do a check, if it's True, change the button to green
otherwise red
however being advanced at a syntax is useless
better to get advanced at programming
ok i did bool = not bool
or a specific field
no, make a value
for example
on = False
on = not on
mk
when u clikc that is
when u click the button, do that
and then
if on:
bg = "black
```"
ok im getting confused anyone wanna cal lol
cya i gtg
where
where r u getting confused
on making the boolian
I just lost this channel but ok
u make the boolian when the program starts
on = False
also just realized that it's spelled as "boolean"
hmm all these years
lmao
ok
lmao what
thats Cpp or C#
c++
yeah
c# isn't that low level
yeah
@gloomy prawn :white_check_mark: Your eval job has completed with return code 0.
001 | ok
002 | posix
same but idk
font_now = "Arial"
font_size_now = 18
def change_font(app):
global font_now
font_now = font_family.get() text_editor.configure(font=(font_now,font_size_now))
font_box.bind("<<ComboboxSelected>>",change_font)```
This changes font for the complete document i only want to change it for selected text, how possible? I tried tags and couple of things and it didnt really worked
@cerulean tinsel thought you might like to know that PySide6 (Qt) hiding/unhiding was about as easy as tkinter, really seems like kivy is the odd one out that cant handle giving and releasing focus properly. Probably going with PySide6 then because the entirety of how tkinter is layed out just makes me go WTF
What's the issue with kivy?
The name 😛
Hey people, I'm currently in an internship where I need to create sensor nodes sending via LoRa some geiger counters data and need a way to get a UI up and running displaying this data
the node and receptor is prettymuch done, just need to do the storing of data in acsv format from an arduino to a raspberry and then, most importantly, an UI
I really want to code it in Python, what would be the best display options apart of matplotlib. I would prefer the creation of an app or of a localhost website
Try PyQt5 and PyQtGraph. This link should get you started with the graphs: https://www.mfitzp.com/tutorials/plotting-pyqtgraph/
that not allowed
hehe, thats good to hear, Me also looked into QT but me english is hard so the doc was not easy to understand, but it looks 10x simpler that Tkinter and less like it works but idk how tf does it work
the main issues was handling focus, i was trying to make a overlay that can be brought up with a global hotkey, and automatically gets keyboard focus in a text input field. This worked. What did not work was rescinding the focus in any way. clicking on another window didn't work, neither did any way of programatically giving up focus or giving it to another window. any key typed on the keyboard would still affect only the kivy textbox, no matter if the window was hidden or minimized.
tkinter and Qt both just automatically give back focus to the window which had it previously when closing/minimizing/hiding
yeah Qt documentation is unhelpful at best, its better to just look at stackoverflow
Also I realized that well Kivy was not built with the purpose that its gonna be a extension to something, instead it is a stand alone user interface, so hiding and showing was not the purpose, it more like making a ( for example ) menu for a game or something or making the UI for a application that buys you ticket or stuff
not that i would at all recommend you to do any of that in python, if you really want to create something of a UI just use a browser with CSS or make it in C# or C++
the issue with using a browser is that i cant well make a overlay in a browser, especially if i want to add transparency at some point
i have seriously considered just using C# tho, but Qt has been working okay so far
if it moves it moves
did you mean "if it works it works"?
ahem ahem
anyone here know how to make searchable for QListView in PyQT ?
class myfilescreen(QDialog):
def __init__(self, maya=False):
super(myfilescreen, self).__init__()
dir = os.path.dirname(__file__)
path = "ui/myFile.ui"
loadUi(os.path.join(dir, path),self)
path = "subjects"
self.dirpath = os.path.join(dir, path)
self.fileModel = QtWidgets.QFileSystemModel()
self.fileModel.setRootPath(path)
self.fileModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
self.listview.setModel(self.fileModel)
self.listview.setRootIndex(self.fileModel.index(self.dirpath))
self.listview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.listview.doubleClicked.connect(self.open_file)
self.fileModel = QtWidgets.QFileSystemModel(nameFilterDisables=False)
def open_file(self):
for file in self.listview.selectedIndexes():
print(self.fileModel.filePath(file), file.data())
file_path = self.fileModel.filePath(file)
os.startfile(file_path)```
here my code
So I'm trying to run my code to where whatever the user enters in the user_input gets printed via button click. I'm not sure how to code it in a way that the button click returns what the user has typed into self.line at that time.
Here's a brief visual of what the app looks like so far:
And here's my whole code: https://paste.pythondiscord.com/haworiluva.rb
I want it so when the user clicks the button (button_1) it prints whatever was typed in the box (user_input_label) in the code via print.
This is PyQt5 by the way.
@coarse mirage not very familiar with PyQt5 but as far as i know you would use signals and slots to accomplish this. The button should have a signal that is triggered when its clicked, so you need to write a slot (a kind of event handler that handles a signal being triggered) which prints out the content. you should be able to get the text content with text = self.line.text().
the way i have seen this done is by looping over the elements in listview and setting their hidden status based on whether they match the search term. This would likely happen in a Slot function (event handler) for typing in a search bar or similar.
on a different note: consider using Pathlib as it provides a nicer way to manage file paths than os.path
can you help write the whole process out of my script ? when you say it like that I seem dont understand what u mean 😦
@lone phoenix
the core filtering should be as simple as
for item in all_listview_items:
if item matches condition:
# set item to shown
else:
# hide item
the issues to consider are:
- how is this code called?
- how can you loop over all items in a listview?
- what will your filter condition be filtering by?
- how can you hide and unhide items?
i encourage you to look up solutions to these individual questions yourself, one search term that i would try is pyqt loop over listview items
thank @lone phoenix
@lone phoenix I managed to make the searching work but somehow my double click to open file function isn't working anymore.
hm, that seems wrong, i assume the line which connects the double click signal and the function it calls are unchanged?
yes it not changed. But I kinda do little trick I found on google with proxy thingy
and then it broke the click function
dir = os.path.dirname(__file__)
path = "subjects"
self.dirpath = os.path.join(dir, path)
self.search.textChanged.connect(self.on_textChanged)
self.fileModel = QtWidgets.QFileSystemModel()
self.fileModel.setRootPath(self.dirpath)
self.fileModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllEntries | QtCore.QDir.Dirs | QtCore.QDir.Files)
self.proxyModel = QtCore.QSortFilterProxyModel(recursiveFilteringEnabled=True, filterRole=QtWidgets.QFileSystemModel.FileNameRole)
self.proxyModel.setSourceModel(self.fileModel)
self.listview.setModel(self.proxyModel)
self.listview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listview.customContextMenuRequested.connect(self.context_menu)
self.listview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.listview.doubleClicked.connect(self.open_file)
self.adjust_root_index()
##########################################################################
# Here the open file broken
def open_file(self):
for file in self.listview.selectedIndexes():
print(self.fileModel.filePath(file), file.data())
file_path = self.fileModel.filePath(file)
os.startfile(file_path)
###########################################################################
def context_menu(self):
menu = QtWidgets.QMenu()
open = menu.addAction("Open")
open.triggered.connect(self.open_file)
cursor = QtGui.QCursor()
menu.exec_(cursor.pos())
@QtCore.pyqtSlot(str)
def on_textChanged(self, text):
self.proxyModel.setFilterWildcard("*{}*".format(text))
self.adjust_root_index()
def adjust_root_index(self):
root_index = self.fileModel.index(self.dirpath)
proxy_index = self.proxyModel.mapFromSource(root_index)
self.listview.setRootIndex(proxy_index)
# End of headacche```
it broken at open_file
the method isnt work why ?
oh wait nvm I got a idea pop up from nowhere.
@spring sand remove the padding from the parent widget
How can I do that :p
ru using designer
import sys
from PySide6.QtCore import Qt
from PySide6.QtWidgets import *
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
menu_widget = QListWidget()
option = ['Manga', 'News', 'Add', 'Plugin']
for i in option:
item = QListWidgetItem(i)
item.setTextAlignment(Qt.AlignCenter)
menu_widget.addItem(item)
text_widget = QLabel("yo")
button = QPushButton("Something")
content_layout = QVBoxLayout()
content_layout.addWidget(text_widget)
content_layout.addWidget(button)
main_widget = QWidget()
main_widget.setLayout(content_layout)
main_widget.setStyleSheet("border: 0px")
layout = QHBoxLayout()
layout.addWidget(menu_widget, 1)
layout.addWidget(main_widget, 4)
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication()
w = Widget()
w.show()
with open("./style/style.qss", "r") as f:
_style = f.read()
app.setStyleSheet(_style)
sys.exit(app.exec())```
okay
setContentsMargins(0, 0, 0, 0)
where is the parent widget ?
Hello there. I want to make an indicator using tkinter. like a speedometer. but i want it for battery. how can i do this??
What battery
car batarry
Hey Can Somebody plz Help Me Edit/make a discord server. Just DM Me If U accept
Do you guys think windows forms is a good GUI starter ?
Or would I better off coding it through QT
Ummm start with tkinter
Man, I think Tkinter would be better, as it is very simple and generates good GUIs (of course, they are not as beautiful as PyQT for example).
Yeah j have tried tkinter before
Not what I'm looking for
I was thinking either Imgui or Winforms/pyqt even though they are harder
I can learn no problem i don't have dedication issues lol
I am just saying tkinter is a good starting point.
If not just go for PyQt.
🤔
You can also use PySimpleGUI, it's based on tkinter, but it has more interesting widget build tools and position managers, and it's interesting in looks and appearance parts.
What are you looking for
Wait i will post an image
I've used PySimpleGUI a lot and it solved a lot of problems that big frameworks didn't solve for me, and it's very simple to understand how it works and use it.
And generates good GUIs
This is what a window looks like in PySimpleGUI:
I had to censor the names becuase of ToS
No
I'm not looking for that sorry
Something modern that doesn't look like Windows Vista
Yea this possible with PyQt and is considered to be common. With tkinter it is possible too, but takes alot of coding
C#
@wise peak Check this, it is possible with tkinter: https://paste.pythondiscord.com/uxucosuvav.rb, but lot of coding, but fairly simple with PyQt.
Is best for what I'm looking for
But why change language? When python can do it?
Python can do everything
Because i don't think the python interface could respond to tasks and that are made in C/CPP or etc
Ive never tried it that's why
Oh
But if you want to go to C#, let's see if the controlled remedies can handle the complexity and syntax of C#
that was a horrible joke
What's this?
QObject::~QObject: Timers cannot be stopped from another thread
just dont share time objects etween threads
Assuming you started the QTimer(s) on the main thread, you cannot change their state (start, stop, setInterval, etc.) from another thread. That is how threading works.
using tkinter to create a calculator application with anEntry and Buttons.
So the buttons have, numbers, right? Everytime I click a button, that number goes to the end of the Entry, so like every number that is put pushes the text to the left. What I want to happen is that the number is inserted to wherever my text cursor position is located in the Entry. Is that possible?
Use <Entry>.index('insert') to get the current position of icursor then insert with that number
from tkinter import *
root = Tk()
def click(num):
cur = e.index('insert')
e.insert(cur,num)
e = Entry(root)
e.pack()
Button(root,text=1,command=lambda: click(1)).pack()
root.mainloop()
Thanks!!!
You can check out Dear pyGui ( it is a upcoming library but still in beta right now )
elaborate - pyGui
silly question - is there some way to prevent a treeview from consuming any objects that are placed below it in the same frame?
minimum reproduction:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
main = tk.Frame(root)
main.pack(fill=tk.BOTH, expand=True)
tk.Button(main, text="I'm perfectly fine.").pack(fill=tk.X)
ttk.Treeview(main).pack(fill=tk.BOTH, expand=True)
tk.Button(main, text="Watch me vanish").pack(side="bottom", fill=tk.X)
root.mainloop()
The button packed below the Treeview will become hidden immediately if you drag up just a little bit, but stays if you drag down, the top one is unaffected. If i fill the treeview with data it seems that the minimum size it begins to fold at expands. Is there a fix for this or something i should be doing instead? (i suppose that answer would be don't put anything under a treeview or don't pack when using treeviews)
I think it is because the minimum height of Treeview is that much and above that is what the treeview is there
strangely enough, if i pack to the bottom before packing the TreeView it works properly... i guess that's the answer then. bit of an odd behaviour though
though i guess i don't quite understand how pack works
it's possible to make a part of the screen change color with the point of view of the viewer variyng verticallyw
can someone help me with little problem:
def listview1(self):
dir = os.path.dirname(__file__)
path2 = "subjects"
self.dirpath = os.path.join(dir, path2)
self.search_subject.textChanged.connect(self.on_textChanged)
self.fileModel = QtWidgets.QFileSystemModel()
self.fileModel.setRootPath(self.dirpath)
self.fileModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs)
self.proxyModel = QtCore.QSortFilterProxyModel(recursiveFilteringEnabled=True, filterRole=QtWidgets.QFileSystemModel.FileNameRole)
self.proxyModel.setSourceModel(self.fileModel)
self.listview.setModel(self.proxyModel)
self.listview.doubleClicked.connect(self.dir)
self.adjust_root_index()
def dir(self):
for file in self.listview.selectedIndexes():
self.dir = file.data()
self.lv.setEnabled(False)
self.lv.setEnabled(True)
self.listview2()
def on_textChanged(self, text):
self.proxyModel.setFilterWildcard("*{}*".format(text))
self.adjust_root_index()
def adjust_root_index(self):
root_index = self.fileModel.index(self.dirpath)
proxy_index = self.proxyModel.mapFromSource(root_index)
self.listview.setRootIndex(proxy_index)
# End of listview1
# ListView2
def listview2(self):
self.path3 = "subjects/" + self.dir
self.dirpath2 = os.path.join(dir, self.path3)
self.search_lesson.textChanged.connect(self.on_textChanged2)
self.file_model = QtWidgets.QFileSystemModel()
self.file_model.setRootPath(self.dirpath2)
self.file_model.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files)
self.proxy_model = QtCore.QSortFilterProxyModel(recursiveFilteringEnabled=True, filterRole=QtWidgets.QFileSystemModel.FileNameRole)
self.proxy_model.setSourceModel(self.file_model)
self.lv.setModel(self.proxy_model)
self.lv.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.lv.doubleClicked.connect(self.open_file)
self.adjust_root_index2()
#################################################################################
def open_file(self):
for file in self.lv.selectedIndexes():
path = self.path3 + '/' + file.data()
os.startfile(os.path.join(dir, path))
#################################################################################
@QtCore.pyqtSlot(str)
def on_textChanged2(self, text):
self.proxy_model.setFilterWildcard("*{}*".format(text))
self.adjust_root_index2()
def adjust_root_index2(self):
root_index = self.file_model.index(self.dirpath2)
proxy_index = self.proxy_model.mapFromSource(root_index)
self.lv.setRootIndex(proxy_index)
# End of listview2```
so
I have above code that show 2 qlistview look sth like this
one qlistview show folder and another one show file in selected folder of other qlistview
Problem:
Every time I switch folder and open the file in other qlistview the file always double
the more I switch between folder. the more file it open double
can someone help me solve this problem ? I been google for solution but I dont seem to find a way.
Can someone help me at #help-cookie pleasee
@vital sentinel Qlink has a different qidget
yo guys does anyone know why i cant see the code on this winform?
this is the source code
@wise peak buddy only python
most ppl here do python so idk and thi is a python specific server
isnt there a channel in here that someone may be able to help me with C# ?
nope this is only python
alright thanks
Help me please
When I change wm_state to zoomed in tkinter, window. resizable (False, False) works crookedly.It hides the task manager
What?
simply put window.resizable hides the task manager in python tkinter
oops the taskbar
hahaha
task manager(((
so that's why no one answered me
It is because when you do root.state('zoomed') it is full screen. Then tkinter automatically rearranges it to fit above the taskbar, but when you disable resizing, it cannot resize and becomes FULL SCREEN
I don't think anyone here answers about tkinter except me(for now)
how to fix it?
Well remove root.resizable(False,False) 😂
ok
If you want to see the issue and the explanation for yourself, then:
import tkinter as tk
import time
root = tk.Tk()
root.state('zoomed')
root.update()
time.sleep(2) # See that it originally fits but disabling resize causes issue
root.resizable(0,0)
root.mainloop()
resizable(0,0)?
0 is same as bool(False)
ok
the window has been updated,but when you click on a square, you can click on a square
but the size doesn't really change
Square?
What did you mean
root.resizable(0,0) 😂 Let me check, just a minute
in general, the element that expands the window is active
I do not think it is possible
I understand, just give me a minute
ok no problem
Ok this is not the most elegant solution, but check if this is what you want:
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update()
h,w = root.winfo_height(),root.winfo_width()
root.state('normal')
root.resizable(0,0)
root.geometry(f'{w}x{h}+0+0')
root.mainloop()
ok, but sorry window is not centralized
You mean there is gap between the window and left border? I don't think I can reduce that gap
yes
Nope, I dont know if I can do anything about it
and why is it there wm_state zoomed had to fix all this
understand
if you reduce this gap nothing will work
What?
if you reduce this gap nothing will work
I do not know how to reduce this gap
i noticed from the very beginning that if you change the size to a smaller one than the full screen resizable will work
it work
thanks
in my main project, this works for some reason
Lol okay 😄


