#user-interfaces

1 messages · Page 77 of 1

orchid stump
#

ok

tawdry mulch
#

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)
orchid stump
#

thanks! I will check it out

#

it works! thank you so much, been struggling

tawdry mulch
tawdry mulch
orchid stump
#

I will check it out

fading basin
#

@shut pine can you help me with something

shut pine
#

yh wassup

fading basin
#

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

shut pine
#

idk anyhting about pyqt5

#

just let the ppl here answer ur question lol

fading basin
#

I want to stretch a button without having to add it in a layout how can you do that ? using pyqt5

spark delta
fading basin
#

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()

verbal storm
#

Can someone here help me please. Why when I type different language into my tkinter entry widget it show question mark(?) ?

spring turtle
#

probably means the font hyou are using doesnt support the character

spring turtle
verbal storm
#

it my country alphabet

spring turtle
#

i mean the font you are using in tkinter

verbal storm
#

Arial

#

or sometime I use times new roman

spring turtle
#

for the text where you use these characters, use the font "Khmer UI"

verbal storm
#

for some reason it still show question mark

spring turtle
#

uh

verbal storm
#

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

spring turtle
#

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

tawdry mulch
#

Is this font pre installed?

spring turtle
#

I din't have to install it so i think yes

verbal storm
tawdry mulch
verbal storm
#

ehh how ?

ebon storm
#

how can i get this effect in adobe or figma

tawdry mulch
#

Which language are you trying to mimic

tawdry mulch
ebon storm
tawdry mulch
ebon storm
#

cause i'm making ui i guess

tawdry mulch
#

Agreed, but not related to python

ebon storm
#

ohh

#

okay

tawdry mulch
#

But if someone knows, they can help you for sure 😄

ebon storm
#

cool

vital sentinel
#
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.

#

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. ://

ivory ember
#

is the "exit.png" in the same dir as the python file/project

vital sentinel
#

yes sir

#

As you can see, the UI Testing.py and exit.png is in the same folder.

verbal storm
vital sentinel
#

PyQt6 to be exact

verbal storm
vital sentinel
#

yeah Qt Designer, but I wanted to learn it by hand.

verbal storm
#

damn that a waste of time lol

vital sentinel
#

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.

verbal storm
#

u can use that program to learn the code from it when u dont know though so u dont need to ask everyone else

vital sentinel
#

What I just don't get is why it's not showing the Icon.

verbal storm
#

wait ops

vital sentinel
#

It needs to be an .ico file?

verbal storm
#

u mean u want it to show on label or icon of the app ?

vital sentinel
verbal storm
#

got it I will try to make it work for u

vital sentinel
#

But right now it's this...

#

It's just blank. There's no icon.

vital sentinel
# vital sentinel

Even though I have both the quit.png and the python file I'm working on in the same folder.

verbal storm
#

okeh I see the problem

#

the path to ur img is incorrect

vital sentinel
#

I tried changing it to /quit.png but it didn't work though.

verbal storm
#

try sth like this ./yourfolder/exit.png

#

i see u in get GitHub folder

vital sentinel
#

Still nada :/

verbal storm
#

can u give me the full path ?

vital sentinel
#

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.

verbal storm
#

..\..\..\..\..\..\..\..\GitHub\exit.png

#

that very long path

vital sentinel
#

Tried it on just the desktop. Still nada.

verbal storm
#

wait min

#

we use wrong slash

#

lol

#

.\yourfolder\exit.png

#

try this

vital sentinel
#

Can we actually use the \ in code?

verbal storm
#

yes it for dir

vital sentinel
#

Still nada

#

This is so annoying haha I don't know what I'm doing wrong.

#

I just copied the code

#

._.

verbal storm
#

../../../../../../../../GitHub/exit.png

#

how abt this ?

vital sentinel
#

It worked...

#

But why though

#

exit.png should be enough what if I put it in another directory.

#

I have to submit this aorijgalkje

verbal storm
#

it some kind of dir thingy it depend on the library how they use it and how they want it to be

vital sentinel
#

hmm yeah I might have to import a library for file handling..

#

or maybe I'll learn that soon in PyQt6

#

Thanks!

verbal storm
#

np

tawdry mulch
vital sentinel
echo berry
#

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

spring turtle
#

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

tawdry mulch
dim arrow
#

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 .

lime monolith
echo berry
opal mulch
#

how to change the indicator image (This is tkinter treeview)

opal mulch
#

yup

#

doesnt work

#

can someone help please?

swift galleon
#

where is the line thats not working

opal mulch
#

there is no error

#

its just not showing the indicator

#

the image

swift galleon
#

let me see

tawdry mulch
opal mulch
#

same thing

opal mulch
swift galleon
#

@opal mulch becuase its ico not png

opal mulch
swift galleon
#

you have that img?

opal mulch
#

ofc

swift galleon
#

@opal mulch can I look at the folder that your project and the png is on

#

why

opal mulch
#

accident

tawdry mulch
#

Wait I do not think that is how you put images on treeview

swift galleon
#

oh

opal mulch
#

u can put an image when using insert tho?..

swift galleon
#

can you open logo .png ?

opal mulch
swift galleon
opal mulch
#

yeah

swift galleon
#

try another way to load images in tkinter

#

let me search

opal mulch
#

ok

tawdry mulch
tender roost
#

anyone know why this stylesheet isnt working

#

i was testin pyqt5

#

Hellloooo

tawdry mulch
tender roost
#

?

#

what about it

tawdry mulch
# tender roost ?

If I am not wrong, you have typed Qlabel it should be QLabel with capital L.

verbal storm
#

can anyone here me please ?

#

how to remove title bar from QDialog ?

#

I know how to remove it from QMainWindow but what about QDialog ?

verbal storm
#

someone ?

verbal storm
#

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)

tender roost
#

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

tender roost
#

the text

#

without it overlapping aything

verbal storm
#

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

tawdry mulch
vestal mauve
#

why is pycharm not working with tkinter

#

??

tawdry mulch
cursive frost
robust valve
#

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.

tawdry mulch
rain jetty
#

elaborate

vital sentinel
#

Using PyQt6, is there a way to change the setFixedSize of a QMainWindow after triggering a QMenu action?

opal geyser
#

anyone good with kivy?

#

please ping me if someone is willing to help : )

vital sentinel
#

!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 :/

vital sentinel
#

I've also been trying to implement some dialog windows for Contact Us and Documentation, but it's not working ._.

verbal storm
#

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
verbal storm
#

anyone help ?

fading basin
honest bloom
#

can i post my open source github New boiler ui here? (pywebview Frameless with custom handler for resize drag and top bar)

vital sentinel
fading basin
vital sentinel
#

I could send in the code for my Calc.

fading basin
vital sentinel
fading basin
#
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
vital sentinel
#

That is honestly what I did before. It won't work.

#

:/

fading basin
#

Ok I will try a different method

#

can you tell what error it shows it would be really helpful

#

@vital sentinel

vital sentinel
#

Nothing just happens...

#

Here's my code right now.

fading basin
#

Ok then that's interesting

vital sentinel
#

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.

verbal storm
fading basin
#

you can use emit or connect there is no connectsignals function that I know of. try that in stead @vital sentinel

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()
fading basin
vital sentinel
#

Of course! Thanks for your time.

fading basin
#

that should do the job

vital sentinel
#

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

fading basin
#

you have to put it after the function

vital sentinel
#
        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?

fading basin
#

wait I posting a haste bin link with the correct format maybe that should work

vital sentinel
#

Thanks!

fading basin
#

or just wait I will just post the link

#

@vital sentinel

vital sentinel
#

Can I just go ahead and change the imports to PyQt6? Since that's what I'm using?

fading basin
#

sure why not

#

but does it work tho ?

vital sentinel
#

There's some indentation errors

#

I'm trying to fix it...

fading basin
vital sentinel
#
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.

fading basin
vital sentinel
#

It doesn't, for now.

#

It just immediately closes

fading basin
#

try removing this part

#

@vital sentinel

vital sentinel
#

which line there?

fading basin
flint axle
#

d

heavy junco
#

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.

turbid crow
ivory ember
turbid crow
ivory ember
turbid crow
#

👍

fading basin
#

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

wooden imp
#

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

fading basin
#

I mean the 1st one

wooden imp
#
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

wooden imp
#

just call .show() only on the window.

onyx spoke
#

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

fading basin
#

@wooden imp

indigo yarrow
#

anyone know how to use kivymd here

#

and knows how to do kivymd to apk

indigo yarrow
tribal path
#

kivymd is just styled kivy

tawdry mulch
tribal path
#

or kivy really - especially if you arent constrained to tkinter

onyx spoke
onyx spoke
tawdry mulch
tribal path
#

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.

tawdry mulch
tribal path
#

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...

quaint orchid
#

does anyone know how i would install qt designer on linux

#

nvm i found it

fading basin
#

Ok is there a way to add Qlabel into QLineEdit

onyx spoke
#

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.

fading basin
# onyx spoke How can I flip this picture according to the movement of the drone? I couldn't w...

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)```

onyx spoke
#

I know that. What I want to do is to be constantly changing. so it will change in real time

fading basin
onyx spoke
#

and ı use tkinter for interface

onyx spoke
tawdry mulch
tawdry mulch
onyx spoke
onyx spoke
#

I need to make an interface. Can someone send me a message to help me?

tawdry mulch
onyx spoke
#

Can we add a specific location on the map to the interface with tkinter? How it is made?

tawdry mulch
#

Everything you actually need is readily available with PyQt but it is not that easy to understand for beginners

onyx spoke
onyx spoke
#

how can I do it. no information found on the internet?

tawdry mulch
onyx spoke
#

i want with tkinter

tawdry mulch
onyx spoke
#

this code not working ??

#

or i dont using?

#

@tawdry mulch

#

How can I add an image to the canvas?

tawdry mulch
#

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

wooden imp
#

Which Qt widget is best used for a duration?

#

but im unsure how to configure it to work with timedeltas

tawdry mulch
wooden imp
#

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)

tender roost
#

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

visual scroll
#

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.

ivory ember
ivory ember
cobalt owl
visual scroll
#

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

ivory ember
#

if you set the QOpenGLWidget as the centralwidget, it doesn't resize or what's the problem

visual scroll
#

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

ivory ember
#

are you setting the centralwidget as a QWidget with a layout or directly adding the QOpenGLWidget

visual scroll
#

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

visual scroll
#

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.

oblique bridge
#

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👇

digital rose
#

can some one help me? With .py to .exe

oblique bridge
#

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

tawdry mulch
timid totem
visual scroll
ivory ember
visual scroll
#

QSizePolicy is no help here

ivory ember
#

maybe try overriding the resize method

#

I'm tryna help you here, but I've never encountered this issue

visual scroll
#

okay

ivory ember
#

sorry

spark prism
#

dang this chat is dead

weak epoch
#

can someone help me with blessed (or curses if i need to switch) in #help-burrito

tawdry mulch
vital sentinel
#

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

zealous gorge
# vital sentinel I want my calculator to play a sound whenever I press a button, and also a loopi...

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

vital sentinel
#

Are those imports prebuilt with python?

#

Oh okay looks like I only need to pip install playsound

vital sentinel
#

It doesn't seem to work..

#

@zealous gorge

vital sentinel
#

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?

zealous gorge
#

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

olive cove
#

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..

vital sentinel
#

Maybe add global count to each of your functions.

#
count = 0
def packData():
   global count
   ...

def moveToNextMeeting():
   global count
   ...
#

@olive cove

olive cove
#

what does that do? @vital sentinel

vital sentinel
#

It makes it so that you're always using the count variable that is outside the functions.

#

!global

proven basinBOT
#

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.

vital sentinel
#

Welp.

#

But global should work though. Just try it out.

olive cove
#

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
native quest
#

!global

proven basinBOT
#

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.

native quest
#

!len

proven basinBOT
#

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.

native quest
#

!pyautogui

olive cove
#

why doesnt it work @vital sentinel ?

orchid niche
#

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...

▶ Play video
spark prism
olive cove
#

using tkinter, how can i only delete buttons from the root?

#

anyone?

ivory ember
# vital sentinel Using PyQt6

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.

hybrid spindle
#

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?

hybrid spindle
#

nevermind! just had to close out the canvas as well as removing the widget. I'm a dummy

tawdry mulch
lime monolith
# olive cove using tkinter, how can i only delete buttons from the root?

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()```
vital sentinel
#
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.

proven basinBOT
#

: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).

sour girder
#

!unmute 311172428049022978

proven basinBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @vital sentinel.

sour girder
#

!paste @vital sentinel use this

proven basinBOT
#

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.

vital sentinel
#

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.

ivory ember
onyx spoke
#

I want to rotate an image in tkinter. how can I do it?

sonic lark
#

Hey guys how do i place text in the center with the grid() in Tkinter I just started learning so please help

sonic lark
#

how do i use padx in pack() funcion in Tkinter

tawdry mulch
tawdry mulch
sonic lark
gaunt willow
#

any other package i could use to make ui, other than tkinter and pyqtinsert_num

arctic anvil
gaunt willow
#

Oh

#

i just hate the .pack() stuff

hybrid spindle
#

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?

analog bison
#

My first thought is if it's threaded a race condition, but if you're in a notebook I doubt it'd be that

hybrid spindle
tawdry mulch
vital sentinel
#

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.

vital sentinel
#

Help :<

onyx spoke
#

I will make a cockpit interface. Which library do you think I should use? (I know intermediate python)

olive cove
digital rose
#

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

mossy geyser
#

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()
onyx spoke
inland carbon
#

hello

#

after i implemented a scroll bar in tkinter

#

my text is left aligned

spring turtle
inland carbon
#

how do i center it

spring turtle
#

There is an argument in widgets 'justify' so you can pass justify='center' and it will center the text

lime monolith
# mossy geyser How do I make a label which tells the amount of CPS, the label I made doesn't se...

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

proven basinBOT
#

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.

real wyvern
#

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??

hybrid spindle
#

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?

real wyvern
#

i think pathlib can do this

hybrid spindle
#

huh...I cant get a double backslash to work

#

thanks booing. I have no idea on your problem haha, sorry mate

real wyvern
#
>>> Path('.').absolute()
WindowsPath('C:/Users/booing')
weak epoch
#

blessed vs curses?

upbeat island
#

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

analog flicker
#

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.

weak epoch
#

if anyone has experience with python prompt toolkit can I get some help in #help-chestnut

worthy ridge
#

@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

novel epoch
#

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

analog flicker
worthy ridge
analog flicker
#

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
        )
mossy geyser
worthy ridge
#

@analog flicker u need to subcalss it with the code i gave u to create a mainwindow to actually hold the UI

analog flicker
#

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.

worthy ridge
#
    class PlayerUI_obj(PlayerUI, QtWidgets.QMainWindow):

        def __init__(self):
            super().__init__()
            self.setupUi(self)
```@analog flicker
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_())
worthy ridge
#
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_())
analog flicker
#

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?

worthy ridge
analog flicker
#

Alright, well thanks again. Have a great day 🙂

meager niche
#

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

upbeat island
#

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

meager niche
#

w.showMaximized()

#

You can only use it once

upbeat island
#

yeah I have show() in


def main():
    app = QApplication(sys.argv)
    main_window = MainWindow.MainWindow()
    main_window.show()
    sys.exit(app.exec_())
meager niche
upbeat island
#

doesn't make a difference, subclassing MainWindow from QWidget works, but subclassing it from QMainWindow doesn't

upbeat island
#

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

young sedge
#

what is the way to pack python installation into standalone installer with all its dependencies for windows?

ivory ember
#

Don't think this is the right channel tho

young sedge
#

windows installers are user interface

ivory ember
#

ig

bitter marsh
#

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?

bitter marsh
# tawdry mulch 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?

tawdry mulch
novel epoch
#

how would i get the number of widgets in a row(grid layout) kivy

novel epoch
#

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

plain coyote
#

pls help

#

need help kivymd

worthy ridge
#

@meager niche u can inegreate matplotlib in Qt

worthy ridge
#

@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

worthy ridge
plain coyote
#

@worthy ridge

worthy ridge
#

i dont do kivy

plain coyote
#

thx for looking

mighty oxide
#

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

noble star
#

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.

ivory ember
noble star
muted vine
#

Are there any good guides for making modern looking UI in python? The ones I found look very 1990s..

noble star
tawdry mulch
#

Then show your code please. @noble star

mental otter
#

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

tawdry mulch
mental otter
#

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.

tawdry mulch
#

So the app just crashes?

mental otter
#

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

tawdry mulch
#

What about without the textvariable.

mental otter
#

same problem, strangely enough the second visible Entry starts with black text instead of gray text

tawdry mulch
#

Ok where else are you using self.parent, within LabeledEntry.

mental otter
#

that's the whole LabeledEntry code

tawdry mulch
mental otter
#

self.master = parent?

tawdry mulch
#

Yup

mental otter
#

seems to do the same thing

tawdry mulch
#

Okay then paste the entire code for me to run it

#

!paste

mental otter
tawdry mulch
#

Okay let me see

tawdry mulch
mental otter
#

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?

tawdry mulch
#

See I confused myself 😛 Which was originally there, self.parent or self.master at line 51

mental otter
#

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

tawdry mulch
#

Okay yes, I was wrong but I had the correct idea. Do you want to know the explanation?

mental otter
#

yeah, what is the difference with parent and master?

tawdry mulch
#

Avoid using self.master at all, stick with self.parent or self.root, better

mental otter
#

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

tawdry mulch
digital rose
verbal storm
#

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

tawdry mulch
worthy ridge
proven basinBOT
#

apollo/app/misc_app/file_explorer.py line 8

class CheckableFileSystemModel(QtWidgets.QFileSystemModel): # Untested```
worthy ridge
verbal storm
#

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.

noble star
#

which one is better : tkinter, kivy or PyQT5 ??

verbal storm
#

pyqt is good cuz it have their own designer

inner iron
#

is this the gui channel?

verbal storm
#

yea but this channel not much out of help

inner iron
#

ight thanks

tawdry mulch
tawdry mulch
verbal storm
#

ehh I don't understand can u like show the solution in code please. I'm kinda new to it

worthy ridge
verbal storm
#

that good too. since I just making it easy to sort my school subjects pdf file and I dont really make sub folder

worthy ridge
noble star
#

PyQT is for native look

tawdry mulch
worthy ridge
#

nope lol

verbal storm
#

it does have style sheet

worthy ridge
tawdry mulch
worthy ridge
#

its easy to hide rows than to repop the full table

verbal storm
worthy ridge
#

file sys model > filter proxy > view u query the proxy to just show valid data

verbal storm
#

oh

#

still doesnt get it

worthy ridge
#

like filter is a mask that u use to hide stuff ur not using techinically

#

file sys model > filter proxy > view data flow diag

verbal storm
#

ok ok I got some glimpse of it thank for the hints

verbal storm
#

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

jagged storm
#

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?

digital rose
gloomy prawn
#

!paste

proven basinBOT
#

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.

digital rose
#

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

digital rose
gloomy prawn
#

changing the buttons background color?

digital rose
#

you can change the button text yes

digital rose
gloomy prawn
#

oh lol made that before

digital rose
#

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.

gloomy prawn
#

background color/changing the text of the button

digital rose
#

when was it againced the tos

digital rose
#

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-

gloomy prawn
#

lol

digital rose
#

i cic

#

😉

#

lol i aint tryna get banned

#

mhm

#

anyways

#

yeah

#

i recommend changing background colour

#

ok to what?

gloomy prawn
#

sadly I can't run stuff overnight cause it's 48°C yes very nice

digital rose
#

of the button

digital rose
gloomy prawn
#

green/red?

digital rose
#

of the button

digital rose
#

or just

#

btn.config("text=auto fish: ON")

gloomy prawn
#

wha

#

no

digital rose
#

yes.

gloomy prawn
#

btn.config["text"] = "blah"

digital rose
#

mk done

digital rose
gloomy prawn
digital rose
#

how tkinter works

#

;/

digital rose
gloomy prawn
digital rose
#

so is it possible to say if its on or off

#

now use requests to make the functionality

digital rose
#

when u click

#

make it black

#

when you click

gloomy prawn
#

if u click it just toggle it using a book

digital rose
#

make it not black, ie, white

gloomy prawn
#

book*

#

FUC

digital rose
#

ok i started python yesterday i have not gone that far

gloomy prawn
#

bool*

digital rose
#

bool

#

people nowdays

#

start python

#

lol

#

and start making guis

#

i know a little c++

#

but thats it...

gloomy prawn
#

I started with b a t c h

digital rose
#

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

digital rose
#

intermediate = pro

gloomy prawn
#

and I made an a n t i v i r u s in batch

digital rose
#

want me to get rid of all of the def funtions?

digital rose
gloomy prawn
#

it just scans filenames in certain directories lmao ok

#

ok back to the code

digital rose
#

ok

#

so what do i do?

gloomy prawn
#

del intermediate

#

del pro

digital rose
#

kk

gloomy prawn
#

import code

digital rose
#

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

gloomy prawn
#

everytime u click the button, do bool = not bool

gloomy prawn
#

to reverse the value

#

then after u reverse it, do a check, if it's True, change the button to green

#

otherwise red

digital rose
#

however being advanced at a syntax is useless

#

better to get advanced at programming

#

ok i did bool = not bool

#

or a specific field

digital rose
#

for example

#

on = False

#

on = not on

#

mk

#

when u clikc that is

gloomy prawn
digital rose
#

and then

#

if on:

#
bg = "black
```"
#

ok im getting confused anyone wanna cal lol

#

cya i gtg

gloomy prawn
#

where

digital rose
#

actaully kinda making sence

#

idk somewhere i can screenie

#

screenshare

gloomy prawn
#

where r u getting confused

digital rose
#

on making the boolian

gloomy prawn
#

I just lost this channel but ok

#

u make the boolian when the program starts

#

on = False

digital rose
#

so like

#

bool on = false?

gloomy prawn
#

wha

#

that's C

digital rose
#

nvm im a idiot

#

yeah lol im used to c++

gloomy prawn
#

also just realized that it's spelled as "boolean"

digital rose
#

hmm all these years

gloomy prawn
#

lmao

digital rose
#

ok i mde the boolean

#

so do i make a if statement?

gloomy prawn
#

in the button click handler yes

#

after u toggle the value (on = not on)

digital rose
#

ok

digital rose
digital rose
#

idk

gloomy prawn
#
cout<<"does this work idk"<<endl;
bool on = false;
#

issit even << lmao

gloomy prawn
#

c++

digital rose
#

yeah

gloomy prawn
#

c# isn't that low level

digital rose
#

yeah

gloomy prawn
#

!e ```py
import os
print("ok")
print(os.name)

proven basinBOT
#

@gloomy prawn :white_check_mark: Your eval job has completed with return code 0.

001 | ok
002 | posix
gloomy prawn
#

w h a

#

I might actually give C++ another go

#

maybe*

digital rose
#

same but idk

gloomy prawn
#

nope.

#

I quit in 6 minutes

#

damn

sudden quiver
#
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
lone phoenix
#

@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

tribal path
#

What's the issue with kivy?

tawdry mulch
#

The name 😛

unreal dirge
#

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

ivory ember
# unreal dirge I really want to code it in Python, what would be the best display options apart...

Try PyQt5 and PyQtGraph. This link should get you started with the graphs: https://www.mfitzp.com/tutorials/plotting-pyqtgraph/

Martin Fitzpatrick

Create custom plots in PyQt with PyQtGraph. One of the major strengths of Python is in exploratory data science and visualization, using tools such as Pandas, numpy, sklearn for data analysis and matplotlib plotting.

digital rose
cerulean tinsel
lone phoenix
# tribal path What's the issue with kivy?

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

lone phoenix
cerulean tinsel
#

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++

lone phoenix
#

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

cerulean tinsel
#

if it moves it moves

lone phoenix
cerulean tinsel
#

ahem ahem

verbal storm
#

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

coarse mirage
#

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:

#

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.

lone phoenix
#

@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().

lone phoenix
verbal storm
#

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

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

verbal storm
#

thank @lone phoenix

verbal storm
#

@lone phoenix I managed to make the searching work but somehow my double click to open file function isn't working anymore.

lone phoenix
#

hm, that seems wrong, i assume the line which connects the double click signal and the function it calls are unchanged?

verbal storm
#

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
#

How can I delete the border ?

#

I use PyQt6

worthy ridge
#

@spring sand remove the padding from the parent widget

spring sand
#

How can I do that :p

worthy ridge
#

ru using designer

spring sand
#
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

worthy ridge
#

setContentsMargins(0, 0, 0, 0)

spring sand
#

where is the parent widget ?

onyx spoke
#

Hello there. I want to make an indicator using tkinter. like a speedometer. but i want it for battery. how can i do this??

onyx spoke
#

car batarry

digital rose
#

Hey Can Somebody plz Help Me Edit/make a discord server. Just DM Me If U accept

wise peak
#

Do you guys think windows forms is a good GUI starter ?

#

Or would I better off coding it through QT

tawdry mulch
digital rose
wise peak
#

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

tawdry mulch
#

If not just go for PyQt.

wise peak
#

🤔

digital rose
#

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.

tawdry mulch
wise peak
#

Wait i will post an image

digital rose
#

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

wise peak
digital rose
#

This is what a window looks like in PySimpleGUI:

wise peak
#

I had to censor the names becuase of ToS

wise peak
#

I'm not looking for that sorry

#

Something modern that doesn't look like Windows Vista

tawdry mulch
# wise peak

Yea this possible with PyQt and is considered to be common. With tkinter it is possible too, but takes alot of coding

digital rose
#

And what are you looking for?

#

Use VB or C# for Windows forms?

wise peak
#

C#

tawdry mulch
wise peak
#

Is best for what I'm looking for

digital rose
#

a tip: Use VB

#

its more simple

tawdry mulch
#

But why change language? When python can do it?

digital rose
#

Python can do everything

wise peak
#

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

tawdry mulch
#

Oh

digital rose
#

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

wise peak
#

Yeah ik

jagged hill
#

What's this?
QObject::~QObject: Timers cannot be stopped from another thread

worthy ridge
ivory ember
jagged hill
#

Ohh

#

Thanks

vital sentinel
#

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?

tawdry mulch
#
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()
vital sentinel
#

Thanks!!!

oak saffron
stray jackal
#

elaborate - pyGui

mental otter
#

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)

tawdry mulch
mental otter
#

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

sly quarry
#

it's possible to make a part of the screen change color with the point of view of the viewer variyng verticallyw

verbal storm
#

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.

vital sentinel
worthy ridge
#

@vital sentinel Qlink has a different qidget

worthy ridge
#

@wise peak buddy only python

wise peak
#

what???

#

oh wrong channel then

#

maybe i should try in offtopic

#

?

worthy ridge
#

most ppl here do python so idk and thi is a python specific server

wise peak
#

yeah but C# servers are non existent

#

they reply every 2 years

worthy ridge
#

most ppl are scared ecause it take 16 gigs to set up the env

#

so obv

wise peak
#

isnt there a channel in here that someone may be able to help me with C# ?

worthy ridge
#

nope this is only python

wise peak
#

alright thanks

pearl yarrow
#

Help me please
When I change wm_state to zoomed in tkinter, window. resizable (False, False) works crookedly.It hides the task manager

pearl yarrow
#

oops the taskbar

#

hahaha

#

task manager(((

#

so that's why no one answered me

tawdry mulch
tawdry mulch
pearl yarrow
#

how to fix it?

tawdry mulch
#

Well remove root.resizable(False,False) 😂

pearl yarrow
#

ok

tawdry mulch
#

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()
pearl yarrow
#

resizable(0,0)?

tawdry mulch
pearl yarrow
#

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

tawdry mulch
#

Square?

pearl yarrow
#

google translator....

tawdry mulch
#

What did you mean

pearl yarrow
#

how to make it so that you can not click on the cube

tawdry mulch
#

root.resizable(0,0) 😂 Let me check, just a minute

pearl yarrow
tawdry mulch
#

I do not think it is possible

pearl yarrow
tawdry mulch
#

I understand, just give me a minute

pearl yarrow
#

ok no problem

tawdry mulch
#

Ok this is not the most elegant solution, but check if this is what you want:

tawdry mulch
# pearl yarrow
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()
pearl yarrow
#

ok, but sorry window is not centralized

tawdry mulch
#

You mean there is gap between the window and left border? I don't think I can reduce that gap

tawdry mulch
#

Nope, I dont know if I can do anything about it

pearl yarrow
#

and why is it there wm_state zoomed had to fix all this

#

understand

#

if you reduce this gap nothing will work

tawdry mulch
#

What?

pearl yarrow
#

if you reduce this gap nothing will work

tawdry mulch
#

I do not know how to reduce this gap

pearl yarrow
#

i noticed from the very beginning that if you change the size to a smaller one than the full screen resizable will work

digital rose
#

Any ideas?

#

Helping someone make a remainder app

pearl yarrow
#

thanks

#

in my main project, this works for some reason

tawdry mulch
#

Lol okay 😄