#user-interfaces

1 messages ยท Page 33 of 1

proper glade
#

so you gotta pass 1 to the second param there when you're adding the label

#

same thing for addwidget minus the index param at the start

digital rose
#

well as i said

#

when i initially add all of the widgets

#

to layouts inside of scrollarea

#

there is like test example

#

that later on when i trigger an event, changes it's values

#

and this initial "sample" of basically a rubbish text that is aligned just fine, so i can't possibly imagine why the same set of labels will suddenly change their positions when just changing their text values

#

i will try what you posted

#

anyways

#

well that worked

#

๐Ÿ˜Š

#

it's hard to comprehend the logic behind pyqt at times

#

spoke too early again, i managed to get the first label to be on very top, but it still takes up as much space as it did before

#

so theres huge space between elements of vbox

#

i tried setting margin

#

for everything already and yet to no avail

#

the thing i noticed is, when content of scrollarea takes a lot of space so that a vertical scrollbar appears

#

all items are aligned properly

#

just as in my first initial state of scrollarea with some test text that does indeed take up that much space, that a scrollbar appears

#

but with less text inside my labels, that basically take up a half of my scrollarea, and that dont trigger the visibility of scrollbar, they are not aligned and have big spaces in between

#

i tried to set max height for groupbox inside of scrollbar and scrollbar itself, but that didn't do it for me

#

but that's a big hint

#

@proper glade

digital rose
#

nvm, fixed it ๐Ÿ˜”

sullen thunder
#

Anyone have any experience working with the PyQt5 built in mouseReleaseEvent ?

sullen thunder
#

Nevermind, figured out my issue and realized a QTimer was a more efficient method of doing things. (also I did get mouseReleaseEvent working just it didn't work for what I wanted.

karmic shoal
#

QTimers are good if you want to update at given intervals

sullen thunder
#

Well, the dilemma I had is I wanted to update a label containing the user net worth when they added a transaction to a ledger. However being they were in different widgets there wasn't a clean signal transfer.

So the timer is a good work around.

I can use the mouse release event to refresh things within a ledger if wanted.

karmic shoal
#

can't you bind a signal sent when the ledger is updated to a function in your widget containing the label?

sullen thunder
#

I haven't been able to find a way to send a signal back between the QDialogs. I know that there is a built in Accept(), Reject(), Done() however those close the dialog. Are there other build in signals?

#

or is there a way to build a signal?

karmic shoal
#

can you not call the function upon dialog accept?

#
if dialog_window.exec_() == QtWidgets.QDialog.Accepted:
sullen thunder
#

That closes my QDialog. I don't want to close it during this refresh

karmic shoal
#

what are you using to take in user input in the QDialog?

sullen thunder
#

All my data is stored in an Sqlite3 databasw

#

And the values are submitted via a pusbutton

karmic shoal
#

oh, then have you tried connecting the pushbutton to the function to update the label?

#

btw, is this project you're working on open source and/or on github?

sullen thunder
#

Maybe I am explaining this poorly.

the target label is housed in a QMainWindow widget. The pushbutton, is housed within a QDialog generated within the QMainWindow MdiArea. As a result I have been unable to figure out a signal that doesn't close the QDialog to return to the QMainWindow to update the target label.

#

no, the project is not open source and/or on git hub at least not currently

#

maybe sometime in the future. I havent' determined my end use of the program.

karmic shoal
#

ah, because your project looks eerily similar to something I plan on working on that involves PySide2, a database, currency of some kind and tables

#

give me a bit I'll try to cook something up

sullen thunder
#

it's a very common project i think. I am bascially building a personal Mint.com application with my own additions

#

so, tbh I might attempt to commercialize it in the end. However, I have a lot of development and testing between now and then lol :p

karmic shoal
#

@sullen thunder are you using PySide2 or PyQt5?

sullen thunder
#

PyQt5

karmic shoal
#

ah, then lemme edit this real quick, I'll send you hastebin paste and you can go check it out

#

@sullen thunder

sullen thunder
#

I will have to check later. Sorry went out for errands

karmic shoal
#

and I have to go to sleep, it's 2am already

#

ping me and I'll check in about 5-6 hours probably

proper glade
#

@digital rose sorry i was asleep. glad you got it all solved.

digital rose
#

yes, i hope you had a good sleep

surreal schooner
#

helo guys i was wondering if you guys knew of any graphical gui designer that worked in ubuntu?
i am really new to gui
i just need it as interface with some calculus scripts

onyx sky
#

what library/framework are you wanting to use?

#

does anyone have a tutorial, or example project or something as far as how you can package a front end of html css and js w python back end like @cococore reccomended above to someone else?

rotund flax
onyx sky
#

ty!!

sullen thunder
#

@karmic shoal I tested the code you provided and it appears to be something I am looking for. However, I need to spend more time investigating it. Unfortunatly I am not getting my weekend coding session in like I enjoy. SO I will have to get to it later.

karmic shoal
#

great, glad to see that helped

sullen thunder
#

@karmic shoal the one issue I am having with i though is. The signal slot appears to be slowing down the program. Like response times are visually slowed down. Not sure why that is though

bitter ingot
#

I need a hand with tkinter. I can't seem to pass params between frames.
I'm also having issues filling a combobox with dict.keys()
I need to pass params (creds, data) from start to main menu
Code is here. Thanks.
https://hastebin.com/inexujilah.rb

winged tiger
#

Hello!

#

Ive got a pyqt label that has a picture on it as an overlay. I have an interactable window beneath it. the label acts as a wall and i cant interact with the thing underneath, how do i fix this

proper glade
#

is there a way to change a qpushbutton's background color without it becoming super ugly?

#

if i use setStylesheet like so:

        self.setStyleSheet(
            f'background-color: {color.name()};'
        )
#

whereas i'd like them to otherwise keep their default look and behaviour and just change the background color from this:

lilac raft
#

Two problems.

A. The headers for this QTableView are not shown, but my implementation is based off of the official Qt documentation.
https://github.com/spikespaz/jvman/blob/master/special.py#L84-L91
https://doc.qt.io/qt-5/model-view-programming.html#creating-new-models

B. Neither is the data shown.
https://github.com/spikespaz/jvman/blob/master/special.py#L51-L82

This is set up with the following code (data population omitted but I can confirm it's valid).

class AppMainWindow(Ui_MainWindow):
    def setupUi(self, window, *args, **kwargs):
        super().setupUi(window, *args, **kwargs)

        self.availableBinariesTableModel = AvailableBinariesTableModel()
        self.availableBinariesTableView.setModel(self.availableBinariesTableModel)
#

I'd like to tackle the problem with the headers first. What's wrong with my headerData method? Why isn't it shown?

karmic shoal
#

looks like you don't call the init method of your superclass?

#
def __init__(self, parent):
    super().__init__(parent)
#

@lilac raft

lilac raft
#

Isn't it inherited?

small cave
#

unless __init__ is overwritten, it should be inherited

nimble lava
#

hey, uhm, silly question but I've been trying to wrap my head around having a function that handles getting an entry through a label in Tkinter but I am stuck between either a key event listener or a button. If I bind a key to the function I need the event keyword in the function to make it run, say ' def pressed(event): ...' but if I want a button to handle it too, the command=pressed gives me a wrong amount of arguments exception (command seems to give 0 while event needs 1 event). Is there a way or workaround to handle both through one function or do i have to use two?

small cave
#

you could use *args as a failsafe since i implied you don't use the event

#

args will be a blank list from the button but contain the event from the key bind

#

however if u don't use it it should be fine

nimble lava
#

that works perfectly for me, thank you. (and yes I wasn't really using the event other than to get the keybind working in the first place)

nimble lava
#

sorry that I have to ask so quickly but I don't quite get why the code before the sleep does not get 'pushed' onto the screen. Is it just because the sleep activates before the window gets a chance to update?

#

oh, and e1 is the entry label, sorry for the confusion there

karmic shoal
#

@lilac raft have you found the solution yet? I can think of one reason that might not work

nimble lava
#

nvm, fixed it. needed an explicit update.

lilac raft
#

Nope. Still blank. Is there a methhod I need to call on the view after updating the model? I tried show

#

@karmic shoal

karmic shoal
#

do you show() the window after or before updating the model?

lilac raft
#

The window? Before. I use show() on the view.

#

Afterwards

karmic shoal
#

wait, before or after?

#

your message has both and I'm confused

lilac raft
#

AppMainWindow.show() is before, obviously, and self.availableReleasesTableView.show() after updating the data

#

but it still oesn't explain the column headers

karmic shoal
#

does the data show?

#

apart from the headers

lilac raft
#

No

#

But it exists and I have confirmed its validity

karmic shoal
#

hm, after you add the data, can you call self.availableReleasesTableModel.layoutChanged.emit()?

lilac raft
#

ahaaaaahhhh

#

No cigar yet but look at this

#
Traceback (most recent call last):
  File "C:\Users\spike\Documents\github.com\spikespaz\jvman\special.py", line 58, in data
    or index.column > self.columnCount()
TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int'
karmic shoal
#

index.column()

lilac raft
#

There was a typo resulting in a function not being calkled and PyQt just swallows the error by default

#

literally missing parenthesis

#

voila

#

Still missing the headers

#

but data is populated!

karmic shoal
#

try comparing the role with != instead of is not?

#

in headerData

lilac raft
#

where

#

Ok

#

That was it

#

forgot that role is an enum

karmic shoal
#

great

lilac raft
#

Thanks man!

#

Do I have to subclass a delegate to get an "enable" checkbox next to each row now?

karmic shoal
#

that I have no idea

lilac raft
#

So I've basically made an API for AdoptOpenJDK

#

And then I decided hey why not make a CLI for it as well, take on Jabba

#

And then I was like Fuck It let's make a GUI

#

So now I have this

#

A DDOS tool for their API

lilac raft
#

The doc says "this slot is called" but that doesn't make sense for the code example I see below it

sullen thunder
#

@proper glade did you ever figure your design question? I am Curious to hear about the style sheets limitations/quirks.

proper glade
#

nah, didnt dig too deep into it. i did do some reading about QStyles but it seemed like a huge pita to maneuver into doing what I want

#

for now i've gone in another direction and am overriding paintEvent directly

#

@sullen thunder

sullen thunder
#

Good to know. I plan to explore the stylesheet in depth in the future. Need to make my app pretty lol

molten flax
#

Trying to bind a command to a <<ListboxSelect>> event, using chars.bind("<<ListboxSelect>>", charload). Using this syntax, the method is passed an event argument, and its executed every time an option is clicked. However, i want the function to take two arguments. I can't get it to work, because passing an argument from the function like chars.bind("<<ListboxSelect>>", charload(Thingy)), it thinks its the event method and gives me a not enough arguments error for what i want Thingy to really go to. Also, if i try i put () on the end of charload, the method is no longer executed on the selection of an option, only one when mainloop is started. Any ideas? Thanks

grim bronze
#

If you want it, here's a recipe for a "keybinding" widget for tkinter.

class KeybindingEntry(tk.Entry):
    def __init__(self, master=None, keybinder_inst=None, target_keybind=""):
        super().__init__(master)

        self.keybinder = keybinder_inst
        self.target = target_keybind

        self.keys_pressed = []
        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<KeyPress>", self.on_key_pressed)
        self.bind('<KeyRelease>', self.on_key_released)

    def on_focus_in(self, event):
        self.keys_pressed = []
        self.update()
        pass

    def on_key_pressed(self, event):
        keysym = self.format_keysym(event.keysym)
        if keysym not in self.keys_pressed:
            self.keys_pressed.append(keysym)
            self.update()
        pass

    def on_key_released(self, event):
        v = "<" + "-".join(self.keys_pressed) + ">"
        setattr(self.keybinder, self.target, v)
        pass

    def format_keysym(self, keysym):
        keysym = keysym.capitalize()
        keysym = keysym.split("_")[0]
        return keysym

    def update(self):
        self.delete(0, tk.END)
        self.insert(tk.END, "+".join(self.keys_pressed))```
#

I find it pretty cool

lilac raft
#

When appending a row of data to the internal data of a superclass of QAbstractTableModel, should I use self.beginInsertRows() and self.endInsertRows() or are those only for the override of the self.insertRows() method?

#

For context these are the relevant lines that I'm asking about. The top highlighted method is a override, a direct port of the example in C++. The bottom is my own, as can be seen from the name conventions. Should I use the notifier functions in add_release() as well?

nimble lava
#

Can anyone explain to me why when I open a file with Pillow and display it, the background changes from white to black?

#

idk why

desert sapphire
#

The background in the first version isn't white, it's transparent.

#

how are you showing this?

nimble lava
#

imported as png, converted to pgm and on a tkinter window. show() has the same result tho

#

so basically I need to add a while background to the original picture, right?

#

or is there a way to leave it at transparent?

desert sapphire
#

PGM is a grayscale image as far as I can see.

#

Without any color.

nimble lava
#

would a gif work then? Tkinter only supports those two

desert sapphire
#

tkinter does those two, but with pillow you can do others

nimble lava
#

well yes but if I want to show it on a tkinter window, I'd have to convert it to one of those formats, no?

desert sapphire
#

As far as I can tell, no.

#

You can just make a tk PhotoImage from a pillow Image

nimble lava
#

o wait, it converts the objects, not the file. I misread that part

#

doesn't really solve my transparency issue since that happens the moment I import my original png.

#

at least from what I can tell after trying show() directly after the initial import

desert sapphire
#

Using a gif could work in that case.

nimble lava
#

I'll try it out

#

ok so

#

gif or not doesn't seem to make the difference but

#

this gives me a transparent image in the tk window

#

but if I use show() on the base image then it loses it. Seems to be a show() issue

#

anyway. Thank you Grote ยฏ_(ใƒ„)_/ยฏ

nimble lava
#

Ok so, I did some more digging and

#

I believe I finally found something that works

#

If anyone is interested:

#

relx and rely are not valid arguments for create_image, sadly but it works just like I want it to.

#

@desert sapphire thanks for the help btw

desert sapphire
#

nice

trim rapids
#

How to you change button color in tkinter

karmic shoal
nimble lava
#

they just don't stop and idk why

karmic shoal
#

when you bind a function, you only bind the function name

#

so that's my_func rather than my_func()

#

the latter will actually call the function, so your functions run whenever it is bound

nimble lava
#

so how do I bind a function if I want to give it parameters? Like, I press <a> and give the character 'a' to the function

karmic shoal
nimble lava
#

if I understand that right, I'd have to make a new partial for each of those. Is that correct?
So it's something like

a_press = partial(player_guess, character='a', canvas=hangman_canvas
#

wait that didn't come out right

karmic shoal
#

yes, that's the gist of it

nimble lava
#

welp

desert sapphire
#

That's pretty cool, hadn't seen it before, like currying made easy.

nimble lava
#

for future reference, how do I do the fancy python code in discord chat?

desert sapphire
#

!codeblock

proven basinBOT
#
codeblock

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print("Hello world!")
```

This will result in the following:

print("Hello world!")
nimble lava
#

thanks

manic lodge
#

pygame.image.get_extended()

i see this in the docs but have no idea how to go around it

#

I wanna stretch an image to X size

#

that returns 1 when printed

proper glade
manic lodge
#

Yeah , ive been doing it for a few hours in help 4 and going through alot of code with it but thank you โค๏ธ

sudden coral
#

@proper glade Which text labels? The things that say "Sampler"? They look like buttons to me.

proper glade
#

@sudden coral the little empty space to the right of the radio.. thing. im assuming it's the place where the text is supposed to go.

#

but since it's empty, it's just taking up space and offsetting the button itself

#

this is what it looks like without the radiobutton so im fairly sure it's not a matter of outer spacing

sudden coral
#

I see. Didn't know they had labels attached to them

#

I'm not seeing any obvious way to remove it from the docs

proper glade
#

same

#

i'm thinking there might be some way to do it via stylesheet

#

but it doesn't seem like there are any good docs for those per widget either

sudden coral
#

That's an interesting approach, though I'm not sure how the label would be selected

#

it doesn't seem to expose the label publicly anywhere

proper glade
#

is it even a label though? or just painted directly

#

๐Ÿคท

sudden coral
#

That isn't hard to find out

#

sec

proper glade
#

oh yeah source code ๐Ÿ˜…

sudden coral
#

Ok so some progress

#

Unexpectedly, qabstractbutton actually provides the functionality for displaying text

#

So let's look there, as the radio button would inherit from qabstractbutton

proper glade
#

on it

#

looks like it is directly painted unfortunately

#

oh no wait, got confused

#

there is a separation between the button and the label, yes

#

in stylesheet form this might be QRadioButtonLabel or QRadioButton.Label. so I'll try those

sudden coral
#

It's not a sub control

proper glade
#

i'm guessing based on the cases there in the source

#

there's both CE_RadioButton and CE_RadioButtonLabel

#

though I can't find where the drawing for CE_RadioButtonLabel actually gets invoked

#

oh man that stylesheet reference is gonna come in so handy. didn't know about that, thank you

sudden coral
proper glade
#

that's only for CE_RadioButton though, no?

sudden coral
#

Yeah

#

Look back in qcommonstyle.cpp

#

when the radio button is drawn

#

it then calls draw again for the label

#

but basically what you need to do is override the paintevent

proper glade
#

ohhhh that's what proxy()->drawItemText is doing

#

i see i see

#

wait no, i went to the wrong point

sudden coral
#

line 1378

proper glade
#

ahh

#

right, I see. so basically I have to reimplement this lol

sudden coral
#

I'm not sure the best way to approach this

#

Maybe use a custom QStylePainter?

#

I never really messed with this "lower level" stuff too much

proper glade
#

i'm gonna try and find out how much control i can get over proxy() and maybe override its drawControl, though that does sound like a pita.

#

QStylePainter huh? i'll look into it

#

thanks so much btw

sudden coral
#

Yeah, that's what drawcontrol is called on

#

At a glance, that may be the way to go

#

Some more useful stuff

proper glade
#

TIL

sudden coral
#

Doesn't seem that bad actually

proper glade
#

yeah, here's hoping ๐Ÿ˜„

sudden coral
#

It is ridiculous that disabling it is not just a standard feature

#

Which makes me wonder if we're missing something obvious

#

Like something in the stylesheet

#

By the way, your UI takes inspiration from FL, right? @proper glade

#

Looks a lot like the channel rack

proper glade
#

@sudden coral yep, im basically reimplementing it inside Reaper

#

and I agree it's quite ridiculous that stuff this simple seems so complicated

proper glade
#

so i added this transparent overlay widget for drawing a curve over the bars and it works well for the most part. unfortunately, when you minimize and restore the window again it just freezes. its paintEvent is never called again. i have no clue why

#

ok, i think i might have discovered a bug?

#

it seems that when you restore minimized windows they don't call changeEvent and therefore the restoration isnt propagated correctly to their children

proper glade
#

ok, i fixed it by making a custom QLayout for overlapping widgets

#
        class OverlappingLayout(Qt.QLayout):
            def __init__(self):
                super().__init__()
                self.items: List[Qt.QLayoutItem] = []

            def addItem(self, item: Qt.QLayoutItem):
                self.items.append(item)

            def itemAt(self, index):
                try:
                    return self.items[index]

                except IndexError:
                    return None

            def takeAt(self, index):
                self.items.pop(index)

            def sizeHint(self):
                return Qt.QSize(1,1)

            def setGeometry(self, rect: Qt.QRect):
                super().setGeometry(rect)
                for item in self.items:
                    item.setGeometry(rect)

            def count(self):
                return len(self.items)
#

definitely needs some work (looking at you sizeHint) but it's getting the job done for now

proper glade
#

ok, that was completely useless. QStackedLayout already lets you overlay widgets.

#

with .setStackingMode

manic lodge
#
if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = event.pos
                for item in objects:
                    if item.frame.get_rect().collidepoint(x, y):
                        item.selected = True
                        
                        print('clicked on image')
                    else:
                        pass
#

So i have this, but it highlights all boxes

#

not just the selected one

#
[<__main__.Piece object at 0x10C8D270>, <__main__.Piece object at 0x10C8D090>, <__main__.Piece object at 0x10C8D0B0>, <__main__.Piece object at 0x10C8D0D0>, <__main__.Piece object at 0x10C96AD0>, <__main__.Piece object at 0x10C96FD0>, <__main__.Piece object at 0x10C96E50>, <__main__.Piece object at 0x10C96F90>, <__main__.Piece object at 0x10C96B90>, <__main__.Piece object at 0x10C96F30>, <__main__.Piece object at 0x10C96F10>, <__main__.Piece object at 0x10C96F70>, <__main__.Piece object at 0x10C96D10>, <__main__.Piece object at 0x10C96FF0>, <__main__.Piece object at 0x10C96ED0>, <__main__.Piece object at 0x10C96530>, <__main__.Piece object at 0x10C96DD0>, <__main__.Piece object at 0x10C96FB0>, <__main__.Piece object at 0x10C96DF0>, <__main__.Piece object at 0x10C96E30>, <__main__.Piece object at 0x10C96B50>, <__main__.Piece object at 0x10C96CF0>, <__main__.Piece object at 0x10C96E10>, <__main__.Piece object at 0x10C96E70>, <__main__.Piece object at 0x10C96E90>, <__main__.Piece object at 0x10C96EB0>, <__main__.Piece object at 0x10C96C50>, <__main__.Piece object at 0x10C96CB0>, <__main__.Piece object at 0x10C961D0>, <__main__.Piece object at 0x10C96BD0>, <__main__.Piece object at 0x10C96C90>, <__main__.Piece object at 0x10C96D30>, <__main__.Piece object at 0x10C96A90>, <__main__.Piece object at 0x10C96CD0>, <__main__.Piece object at 0x10C96D70>, <__main__.Piece object at 0x10C96D90>, <__main__.Piece object at 0x10C96DB0>, <__main__.Piece object at 0x10C968B0>, <__main__.Piece object at 0x10C96B70>, <__main__.Piece object at 0x10C96650>, <__main__.Piece object at 0x10C96970>, <__main__.Piece object at 0x10C96BB0>, <__main__.Piece object at 0x10C96BF0>, <__main__.Piece object at 0x10C96C10>, <__main__.Piece object at 0x10C96C30>, <__main__.Piece object at 0x10C96990>, <__main__.Piece object at 0x10C96A70>, <__main__.Piece object at 0x10C96290>, <__main__.Piece object at 0x10C96410>, <__main__.Piece object at 0x10C96AB0>]
#

(this is objects)

#
class Piece:
    def __init__(self, frame, x, y):
        self.frame = frame
        self.x = x
        self.y = y
        self.selected = False
    def draw(self, screen):
        screen.blit(self.frame, (self.x, self.y))
        if self.selected == False:
            width, height = self.frame.get_size()
            pygame.draw.rect(screen, (0,0,0), (self.x,self.y,width,height), 4)
        else:
            width, height = self.frame.get_size()
            pygame.draw.rect(screen, (255,0,0), (self.x,self.y,width,height), 4)
#

this is my class

#

Will only work when i click the first one

#

and then it highlights them all

#
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                x, y = event.pos
                for item in objects:
                    width, height = item.frame.get_size()
                    if item.x in range(x,x+width) and item.y in range(y+height):
                        print(item)
                        item.selected = True
#

this somewhat improved it

#

however still not working as indended

#

Each blit is 120, 126 in size

#

If i click on
(0, 0)
720 504 is the item.x , item.y

#

(its randomised)

#

@tight bear Im stuck again ๐Ÿ˜ข

tight bear
#

Could you pastebin your code so I could test it?

manic lodge
#
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                x, y = event.pos
                print(event.pos)
                for item in objects:
                    print(item.x, item.y)

this bit is me testing the corners and stuff

#

would i need to do something like self.newcoordx and self.newcoordy

tight bear
#

Been a while since I've done pygame collision checks, but there oughta be something.

manic lodge
#

was looking here

#

but couldnt see anything

tight bear
#

Ok, you do want to use collidepoint, but there's something with the placement.

#

Because the rect doesn't know about the self.x and self.y

manic lodge
#
sprites_clicked = [sprite for sprite in all_my_sprites_list if sprite.rect.collidepoint(x, y)]
#

could this be useful?

tight bear
#

Nah.

#

If you change back to using piece.frame.get_rect().collisionpoint(x,y), it triggers correctly when you press the top left piece.

#

As in, it triggers all pieces, because that's where they are technically placed.

manic lodge
#

collidepoint?

tight bear
#
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
    x, y = event.pos
                    
    for item in objects:
        # Deselect all pieces
        item.selected = False

        # Select targeted piece
        if item.frame.get_rect().move(item.x, item.y).collidepoint(x, y):
            item.selected = True
manic lodge
#

.move?

tight bear
#

This seems to work.

#

So, the problem with the collision detection is that the rect/image is technically placed at (0,0)

#

Blit doesn't move an image, it just draws it at a location.

#

So all images are piled up at 0,0 which doesn't work for the intended collision check. I'm sure you could move the image some other way earlier, or blit does something odd.

manic lodge
#

Yeah most likely, ill check it

#

Yeah that works nicely,

tight bear
#

In either case, you could move the collision check into the class itself, like a click where it does that code called for each piece atm.

#

You'll notice that the select boxes overlap weirdly, and that's because they're currently outside of the image due to widthxheight and thickness 3

manic lodge
#

yeah i gathered that, would a fix be to have a border?

#

Or just to reduce thickness

#

thickness 2 seems to work fine

tight bear
#

Pygame's shape draw functions are kind of awful, so you'll just have to try it out.

#

Like it's unclear whether the lines points are in the middle of the thickness or on the top left corner

#

And it's different for the right and bottom

manic lodge
#

yeah its weird in that way

#

i saw that earlier

#

tried to select bottom right

#

and it was off the screen

#

xD

#

its like a fade

tight bear
#

Even if you draw the thickness perfectly inside of the frame, the edges are circular

manic lodge
#

Thats weird...

#

Why would they do that

#

in a square..?

#

Right, ill be back ina few hours got to go to college ๐Ÿ˜›

#

ty for that โค

tight bear
#

๐Ÿ‘

manic lodge
#

@tight bear i feel like im super close to switching them and it just doesnt seem to want to stay like it, i can see it flicks to it for a second then goes back

#
        selected=[]
        for item in objects:
            if item.selected == True and item.selected not in selected:
                selected.append(item)
                if len(selected)==2:
                    selected[0].swap(screen, selected[1])
                    print(selected)
                    for item in objects:
                        item.selected = False
            item.draw(screen)
tight bear
#

I would suggest keeping the piece.selected as your only data. When clicking on a piece, check if it is not selected and loop through all other pieces.

#

If another piece is selected, do a swap of their x/y

manic lodge
#

i was just being stupid

#

I switched there frames aswell

frigid ore
#

i have a problem with the layout. i have two tabs in my GUI. In the frist one i have a QHBoxLayout and QVBoxLayout. Here is the source Code: ``` h = QHBoxLayout()
h.addWidget(self.fjsr)
h.addWidget(self.zeile)
h.addWidget(self.uploadbtn)
v = QVBoxLayout()
v.setAlignment(Qt.AlignTop)
v.addLayout(h)

    self.tab1.setLayout(v) ``` I send u a picture how the layout looks like:
#

Then i have the second tab where the buttons are created withe the loop: ``` box = QVBoxLayout(self)
self.tab2.setLayout(box)

    scroll = QScrollArea(self)
    box.addWidget(scroll)
    scroll.setWidgetResizable(True)
    scrollContent = QWidget(scroll)
    scrollLayout = QVBoxLayout(scrollContent)
    scrollLayout.setAlignment(Qt.AlignTop)

    scrollContent.setLayout(scrollLayout)
    scroll.setWidget(scrollContent) ``` there i create the buttons in a loop and can scroll. i send u a picture:
#

how can i change the layout in the second, that it looks like the first tab?

manic lodge
#

Hey,

def gameLoop(width, height, random_indicies, screen, frames, split,objects):
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            x, y = event.pos      
            for item in objects:
                if item.frame.get_rect().move(item.x, item.y).collidepoint(x, y):
                    item.selected = True
        
        selected=[]
        for item in objects:
            if item.selected == True and item.selected not in selected:
                selected.append(item)
                if len(selected)==2:
                    selected[0].swap(screen, selected[1])
                    for item in objects:
                        item.selected = False
            item.draw(screen)

        pygame.display.update()
        msElapsed = clock.tick(60)
#

How would i make it so that no item is selected if after a sweap?

real quarry
#

idk

#

xd

manic lodge
#

each item in object has a .selected in

#

@tight bear ... i need help again :L

sonic bridge
#

@Jan you could use nested layouts, multiple horizontal inside a vertical. Or grid layout.

tight bear
#

@manic lodge Working on a project atm, but can help out later!

#

You deselect all items by looping over them and setting select to False.

manic lodge
#
                    for item in objects:
                        item.selected = False
#

I did that here but it didnt seem to work

#

and no worries! gl on ur project โค

#
                if item.frame.get_rect().move(item.x, item.y).collidepoint(x, y):
                    item.selected = True
                    break
#

this sets it back to true when i get back round

#

I dont get how though because:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:

#

wouldnt be true

manic lodge
#

MOUSEBUTTONDOWN is dodgey

#

used

#

pygame.mouse.get_pressed()[0]==1:

tight bear
#

@manic lodge Solved it?

manic lodge
#

Somewhat... XD

#

Its a little buggy but it somewhat works now

tight bear
#

Pastebin it!

manic lodge
#

Ok, theres one problem rn

#

Ive added pokemon and dog images at random too it

#

So youll have to download 800 pokemon imgs

#

or just change it to a name

tight bear
#

Nah, can probably change the name.

manic lodge
#

yeha u can

#

awh xD

#

It picked me up for spam

#

@tight bear ๐Ÿ˜ƒ

tight bear
#

What was wrong with mouse button down?

manic lodge
#

it kept going

#

like all the time

#

Even after loop

#

Also, right click unselects it

tight bear
#

Sure, but you could still use pygame.MOUSEBUTTONDOWN and event.button

manic lodge
#

I mean i did try still using them it just didnt work

#

Might of been something i was doing

tight bear
#

When it comes to swap, there's an elegant solution to swapping two variables

manic lodge
#
        store = [item2.x,item2.y,item2.frame]
        item2.x, item2.y,item2.selected = self.x, self.y, False
        self.x, self.y, self.selected = store[0], store[1], False
#

I tried this

tight bear
#
    def swap(self, other):
        self.x, other.x = other.x, self.x
        self.y, other.y = other.y, self.y
        self.selected = False
        other.selected = False
manic lodge
#

we need screen? or draw?

tight bear
#

Well, the pieces are drawn every frame, so changing their position will update the place they're drawn immediately after the events.

#

The only place you'd ever need blit is in draw. Elsewhere you could update x,y however you want.

manic lodge
#

ohhh! that makes a lot of sense... because were drawing it on swap then draw

#

when we should just do draw

tight bear
#

Give me a moment, got some food in the oven

manic lodge
#

Alright no worrie

tight bear
#

Ok, I think the logic might've been a bit warped, trying to swap pieces in the update as long as there are some in a buffer.

#

Any kind of swapping should occur right as you get a mouse click event.

#

How it could be structured is this:

  1. Try to find a selected piece (loop over all and store in a variable if found)
  2. Do mouse collision check with all pieces to see if one is found
    3.1) If selected piece exists, swap current piece and selected piece
    3.2) If no selected piece exists, set selected
manic lodge
#

oh and that should be in the event?

tight bear
#
def gameLoop(width, height, random_indicies, screen, frames, split,objects):
    clock = pygame.time.Clock()

    while True:
        # Check events
        for event in pygame.event.get():
            # Quit event
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()

            # Mouse click event
            if event.type == pygame.MOUSEBUTTONDOWN:
                mx, my = event.pos      
                if event.button == 1: # Left

                    # Try to find selected
                    selectPiece = None
                    for item in objects:
                        if item.selected:
                            selectPiece = item

                    # Look for click collision
                    for item in objects:
                        if item.collision(mx, my):
                            if selectPiece:
                                # Another piece is selected: swap
                                selectPiece.swap(item)
                                selectPiece.selected = False
                            else:
                                # No other pieces are selected: select
                                item.selected = True

                if event.button == 3: # Right

                    # Deselect all pieces
                    for item in objects:
                        item.selected = False


        # Draw items
        for item in objects:
            item.draw(screen)

        pygame.display.update()
        msElapsed = clock.tick(60)
#

Yeah, or to make it look much nicer, I'd suggest moving it into a function.

#

Such as clickSelect or deselect perhaps.

#

Also, in this example, I changed the swap function like shown before, and moved the weird collision rect thing to Piece.

#
    def swap(self, other):
        self.x, other.x = other.x, self.x
        self.y, other.y = other.y, self.y

    def collision(self, x, y):
        rect = self.frame.get_rect()
        rect = rect.move(self.x, self.y)
        return rect.collidepoint(x, y)
#

The only thing swap should do is swap their positions (or images). Collision checks with the mouse x,y and returns True if it is targeted.

#

When a swap occurs, you know that the only selected piece has to be selectedPiece, which we can safely deselect.

manic lodge
#

this makes a lot more sense structurely

#

Gotcha, so we never have 2 selected pieces

#

Its always just 1 , with another one being found

tight bear
#
# Try to find selected
selectPiece = None
for item in objects:
    if item.selected:
        selectPiece = item

# Look for click collision
for item in objects:
    if item.collision(mx, my):
        if selectPiece:
            # Another piece is selected: swap
            selectPiece.swap(item)
            selectPiece.selected = False
        else:
            # No other pieces are selected: select
            item.selected = True
#

It's all about this code here, when the mouse is clicked.

manic lodge
#
selectPiece = None
for item in objects:
    if item.selected:
        selectPiece = item
#

this finds THE one selected

#

Ok, understood

tight bear
#

Yep yep! What happens when no piece is selected?

manic lodge
#

it deselects

#

wait no

#

If no other piece is

#

it selects

tight bear
#

In those four lines you posted. What happens to selectPiece?

manic lodge
#

If another piece is

#

it gets assigned the item where its selected

#

aka the only one which is selected

tight bear
#

And if there are no selected?

manic lodge
#

Nothing, it carries on until something is selected

tight bear
#

Yeah, and then selectPiece will remain None

#

This is why you can call if selectPiece: later to see whether there is one or not.

#

Anyway, you get the hang of it

#

Next up, you need some kind of check for when all pieces are in place!

#

Something that oughta be called after a swap, such as checkIfDone

manic lodge
#

Should we make it so it turns green if its in the right position

#

So that we can check for each piece

tight bear
#

Sure! Could put that code in the Piece.

#

Definitely playable now, which is neat~

manic lodge
#

yeah definetly! its coming together nicely!

#

if the image is done

#

the collision will be in that spot?

tight bear
#

What do you mean?

manic lodge
#

if the errr image is in the right position

#

like small blit/image

tight bear
#

I think what would be best is to give each Piece its "correct" position when it is created. You have that knowledge when you create them.

#
for index, frame in enumerate(frames):
    num = random_indicies[index]
    x = width * (num % split[0])
    y = height * (num // split[0])
manic lodge
#

yeah the x,y is the correct coords if im not mistaken?

tight bear
#

You have index, which is the correct ordered index of the frame, and num, which is chaotic random.

#

Yeah, you could calculate the correct x,y in just the same way, using index instead of num

#

Could calculate both, pass it into Piece constructor and save x,y as coordinates and goal_x, goal_y as the goal to compare with later.

manic lodge
#

piece = Piece(frame, x, y)
so when u have this

#

we need to save it as self.goal_x and self.goal_y?

tight bear
#

piece = Piece(frame, x, y, goal_x, goal_y)

#

Then you need to add these to __init__ and save them into self the same way.

manic lodge
#
goal_y = height * (index // split[0])
tight bear
#

Lastly, you could make a function in Piece such as isCorrect or something that compares these coordinates and can be called in draw or upon swap.

#

Yeah, that looks alright, same way as the y coordinate.

manic lodge
#

yea but with index not num ๐Ÿ˜ƒ

tight bear
#

To explain how the weird index % split[0] and index // split[0] works, we can look at what index, x, y are.

#
index: 0     x: 0    y: 0
index: 1     x: 1    y: 0
index: 2     x: 2    y: 0
index: 3     x: 3    y: 0
index: 4     x: 4    y: 0
index: 5     x: 0    y: 1
index: 6     x: 1    y: 1
index: 7     x: 2    y: 1
index: 8     x: 3    y: 1
index: 9     x: 4    y: 1
index: 10    x: 0    y: 2
index: 11    x: 1    y: 2
index: 12    x: 2    y: 2
index: 13    x: 3    y: 2
index: 14    x: 4    y: 2
manic lodge
#

looks somewhat like how u do binary splits?

tight bear
#

X will cycle from 0 to (width-1) and Y will become each line, ticking up as index goes past width.

#

More or less.

#

It's just rather useful math to know.

manic lodge
#

Yeah so each x, y has an index

#

So for each line

#

it has width amounts

#

and for each width amounts it has a y value attached

#
   def isComplete():
        if self.x,self.y == self.goal_x,self.y:
            self.isCorrect = True
        elif other.x,other.y == other.goal_x,other.self_y:
            other.isCorrect = True
tight bear
#

What is other?

manic lodge
#

the swapped one

#

def swap(self, other

tight bear
#

Well, the icComplete should only really return True or False whether that one piece is correct or not.

#

Pieces shouldn't try to keep track of each other.

#

Plus, there's no other parameter in the function, so it'll result in an error.

#

Plus, you're comparing y with y.

manic lodge
#

yeah i gathered that, also i made the same mistake as before

tight bear
#

And self_y doesn't exist.

manic lodge
#

im putting it in swap but it draws every turn

tight bear
#

Well, first off, what would you like to use correct check for?

manic lodge
#

if self.x == self.x_goal

#

and same for y

#

for each Piece

tight bear
#

No, I mean, what could you use the isCorrect check for?

manic lodge
#

if its in the right position?

tight bear
#

Was thinking more about where you could try using it right now.

#

Say, in draw for instance. If it's correct, draw a green border.

manic lodge
#
        elif self.isCorrect == True:
            width, height = self.frame.get_size()
            pygame.draw.rect(screen, (0,255,0,50), (self.x,self.y,width,height), 2)
#

Ah, i did this just on insentive xD

tight bear
#

Yeah, tis nice!

manic lodge
#

should i do

#

if its not correct

#

check if it is?

tight bear
#

Two ways to do this. Now you're setting self.isCorrect to be a value, so you will need to set it in init and update it upon swap.

#

An alternative is that you have a function like self.isCorrect() that returns True or False, just doing a check.

manic lodge
#

right so

#

When items are swapped

#

it checks if they become complete

tight bear
#

Sounds good.

manic lodge
#

So we have to take through both self and other so we can see both

#

and then if

#
    def isComplete():
        if self.x,self.y == self.goal_x,self.y:
            self.isCorrect = True
        elif other.x,other.y == other.goal_x,other.self_y:
            other.isCorrect = True
#

but self_goal

tight bear
#

I would not recommend sending other into that check.

#

Each piece should be able to determine its own state.

manic lodge
#

wouldnt that then go in draw

#

instead of swap?

#
self.isCorrect = isCorrect(self)
tight bear
#
def isCorrect(self):
    return (self.x == self.goal_x) and (self.y == self.goal_y)
#

Here's the simplest version.

manic lodge
#

ah, forgot u can put "and" in returns

tight bear
#

Alternative is spreading it out to make it more readable.

manic lodge
#

I understand that, so i think itll be fine

tight bear
#

Anyway, then all you need in draw is if self.isCorrect():

manic lodge
#

and then u wont even need self.isCorrect

#

in init

tight bear
#

Well, you can't really name both the function and variable the same thing.

manic lodge
#

isComplete

#

not correct

tight bear
#

Note that whenever you check if a boolean == True, it is the same as writing just if boolean:

#

For boolean == False, you can use if not boolean:

manic lodge
#

elif self.isComplete(): for example?

tight bear
#

Anyway, you might notice that it won't draw any green borders. Something else is drawn first.

#

Sure.

manic lodge
#

and if self.selected?

#

if not self.selected

#
if not self.selected and not self.isComplete():
tight bear
#

Just change the order.

#

If it is correct, then it is not selected.

#

So not selected will always draw first.

#

Try flipping it around. If no other special cases exist, draw it black. First check if selected, red, or complete, green.

manic lodge
#
    def draw(self, screen):
        screen.blit(self.frame, (self.x, self.y))
        if self.isComplete():
            width, height = self.frame.get_size()
        elif self.selected:
            width, height = self.frame.get_size()
            pygame.draw.rect(screen, (255,0,0,50), (self.x,self.y,width,height), 2)
        else:
            width, height = self.frame.get_size()
            pygame.draw.rect(screen, (0,0,0,50), (self.x,self.y,width,height), 2)
#

like so?

tight bear
#

Mhmm!

#

If you want to keep it similar to the self.selected, you could indeed do something like self.correct and set it correctly whenever you do a swap.

#

However, in puzzle games it might not be super fun if you know immediately when a piece is correct.

#

But rather only when all pieces are correct and you're done.

manic lodge
#

exactly! so if i create one with
for item in object:

#

if item.isComplete()

#

x+=1

#

if x == len(objects):

#

turn all green

tight bear
#

Yep, that works.

manic lodge
#

is there a way to untransparent items?

#

eg:

tight bear
#

Yeah, you can start with a fill.

#

surface.fill( (255,255,255) )

manic lodge
#

so in startup

#

itll be screen?

#
    screen = pygame.display.set_mode((size[0], size[1]))
    screen.fill((255,255,255))
#

then it turns white

#

but things still duplicate

tight bear
#

That works as well. That fills the background.

#

However, for each piece, you need to fill the surface before blitting the image.

manic lodge
#

oops xD

#

frame.fill((255,255,255))

#

good white full game xD

#

im confused

#

it just

#

whites the whole

tight bear
#

Hrm, could be that you're filling in the image, which overwrites it.

#

For now you could fill the screen though.

manic lodge
#

yeah i got that

#

id need to do it before theyre made

tight bear
#

Might also want to fill it before drawing all objects. Might notice that if you start moving pieces outside of their positions, the background will look trippy without fill.

manic lodge
#

that bad

tight bear
#

Definitely not. That is not Piece's responsibility.

#

Plus only one piece would show, most likely.

manic lodge
#

yep

#

as itll fill the est

#

rest*

#
    while True:
        screen.fill((255,255,255))
#

right, well i have to rest so ill speak tomorrow! thanks again ur a life saver!

tight bear
#

๐Ÿ‘

manic lodge
#

You must have coded for sucha long time, ur so smart

tight bear
#

Well, started with Game maker in 7th grade, drag and drop programming.

#

Later in university I learned Python. Done it for 6 years.

#

Once you've solved a specific problem a few times, you know how to do it right the next time you see it.

manic lodge
#

6 years is a long time and yeah problems are easier when theyve already been solved :p

#

Im in college just started this year

#

(17)

tight bear
#

Keep it up!

manic lodge
#

Thanks man! Thanks for the help its really motivating and having someone there to push me forward to learn much faster is so helpful and im so grateful

trim rapids
#

How do you postition widgets in a tkinter

#

position*

karmic shoal
#

note that you can only use 1 layout in a master window

dawn schooner
#

hello, how to kill Pyqt5 window?

karmic shoal
#

what do you mean by kill?

#

@dawn schooner

dawn schooner
#

terminate the pyqt5 mainWindow

#

@karmic shoal

karmic shoal
#

right

#

your main window class inherits mainWindow?

dawn schooner
#

self.window = QtWidgets.QMainWindow()

karmic shoal
#

self.window.close() closes that window

dawn schooner
#

oh lemme try

#

still wont close ๐Ÿ˜ฆ

karmic shoal
#

it's self.window.close(), just noticed I made a typo

#

if you did that an it still won't close, can you post your code?

dawn schooner
#

yea i got error when it was windows so i tried window

#

still samae

#

Here it is bro, plz check and help me

#

line 105 andd line 120

#

lemme change windows in line 120

#

that window wont go ๐Ÿ˜ฆ

#

tried many thing

karmic shoal
#

actually, I'm not sure why you have if __name__ == '__main__': inside the class

#

!e

class Test:
    def __init__(self):
        print("init")
    if __name__ == "__main__":
        print("main")

test = Test()
proven basinBOT
#

@karmic shoal Your eval job has completed.

001 | main
002 | init
karmic shoal
#

can you try having whatever is in main in a class method, then run that method in __init__?

dawn schooner
#

i want to run two function at the same time

#

the gui and the voice

#

it say's lisa is not defined

karmic shoal
#

that's because you have it as def lisa(): in your class

#

if you put a @staticmethod decorator on top of def lisa():, you should be able to call it as self.lisa

dawn schooner
#

but it wait for audio to finish than it brings up the Gui

#

Plz Kosa any way i can run both Gui and Voice of lisa?

karmic shoal
#

can you show me the code now?

dawn schooner
#

with your edits of staticmethod?

karmic shoal
#

the whole thing

dawn schooner
#

i have three different code

#

this one is just taking input and inserting into data

karmic shoal
#

you had lisa running with multiprocessing, but then you removed it, can you try adding that back in?

dawn schooner
#

Yea this one plays Audio as well as display Gui

#

i think when i run os.system(python3 first.py) it wont move onto next command until thata script is finished

#

because keyboardintterupt is working now

#

because of self.window.close

#

ok now atleast i know self.window.close works

#

Now i understand why it won't work at the same time

#

Thank you @karmic shoal โค

#

i've found an alternative by using a gif splashscreen for 5 sec while it plays audio and later on into the gui

#

i'll use static method dnw

mighty frigate
#

is there some Qt user somewhere ?

#

I have a bit of a pickle

#

So, i'm making this ruler

#

I used a QSplitter with some customization over the handle

#

but err...

#

due to the handle size, I can't really move them on the extrem top or bottom

#

any idea ?

#

rn, I'm trying negative margin/padding, that's how deseperate I am

proper glade
#

@mighty frigate you could scale down the rainbow rectangle so the top and bottom edges line up with the handle

#

and fill the top/bottom with transparent rectangles

#

then there's an attribute you have to turn on, WA_TranslucentBrackground or something like that

#

is the rainbow a QFrame?

dawn schooner
#

Tutorial for PyQt5 ? or examples on how to create properly

sullen thunder
#

@dawn schooner What kind of tutorial are you looking for? How indepth do you want to go?

#

http://zetcode.com/gui/pyqt5/

This provides a nice introduction into how PyQt5 works. Its 100% manual in that you build the Ui and the Functionality.

If you want to Learn Qt Designer I suggest looking around Youtube or looking for a book. A couple do exist

dawn schooner
#

A python app in which i can input display input and output of terminal??

#

pyqt5

#

difficult to find so far

#

wanna embed terminal in pyqt5

dawn schooner
#

i want a pyqt window like Cortana ๐Ÿ˜

proper glade
#

you could take a look at the source for some ideas at the least

dawn schooner
#

ohh man that's a lot ๐Ÿ˜ฆ

#

also i'm not that pro to do advanced coding

proper glade
#

ah i see. hmm i havent been able to find any ones alrady made for pyqt

#

oh wait, they have a pyqt binding there

dawn schooner
#

maybe i can make a window

proper glade
dawn schooner
#

take my input into a textbox

#

and display output in textbox

#

i just realize

#

that would be simpler

#

right?

proper glade
#

yep, that's always an option

dawn schooner
#

since i don't want to type any commands , just a program like cortana

#

to take microphone input

proper glade
#

though youd have to handle things like ctrl+c for termination and the like if you want that

#

ah i see

dawn schooner
#

i just realize that ohh that was simpler than i thought itd be

#

just making it complicated xD

onyx sky
#

i'm trying to connect my exit handler using pyside2 but all i'm seeing is overloading a new closeEvent method on your class, but i'm not having it as part of a class. Is there a way to do that?

mighty frigate
#

@proper glade y it is (QSplitter)

proper glade
#

ohh i see, so the rainbow is drawn on the QSplitter itself

mighty frigate
#

y as stylesheet

proper glade
#

y?

mighty frigate
#

yes

proper glade
#

oh

#

hmm well the only thing i can recommend then is to maybe

#

use a QGraphicsView and add the splitter, use stylesheet to remove its border and background + a rectangle with the rainbow inside it

mighty frigate
#

oh good idea

proper glade
#

and make sure the rectangle is below the splitter of course

mighty frigate
#

I can't do that tho :/

#

the ruler will already be in a QGraphicsView

#

in my experience, a QGraphicsView inside another one is recipie for disaster

proper glade
#

how so

#

and in any case, you could add the rectangle and splitter separately to the original QGraphicsView then

mighty frigate
#

from what I remember (it was some years ago) it can induce problems like fonts breaking, no transparency (black), etc

#

rn I left that issue sitting

#

i'm working on the graduation

proper glade
#

graduation? from uni/college?

#

ohh ruler graduation

mighty frigate
#

yes sorry :p

#

my english isn't perfect, feel free to correct me

proper glade
#

haha no you're fine

#

took me a sec to get the context

nimble lava
#

can someone help me figure out why the lines and boxes don't line up :/
image is scaled down to 600 x 450 from 2048x1536

#

so boxes should be 50px wide

#

box_size is 600/12, so 50

half latch
#

The boxes might be the issue actually

#

Rather than the lines

desert sapphire
#

I see 2 sets of lines

nimble lava
#

yes the ones that don't line up with the circles are from the image used as background

desert sapphire
#

Are those light lines from the background image?

nimble lava
#

yes

desert sapphire
#

My best guess is that it's a scaling issue.

#

Or the orginal squares on the image aren't the exact size

nimble lava
#

my only explanation is that 2048/600 and 1536/450 aren't exact integers and might cause havoc. Everything else lines up nicely with the resolution i chose.

desert sapphire
#

Do the lines overlap if you do the 2480x600 version instead of the scaled one?

nimble lava
#

original is 2048x1536 and I can't display fit the whole thing but doesn't seem to be the case

desert sapphire
#

You don't need to see all to see if they line up

nimble lava
desert sapphire
#

Looks like the light lines are just a bit bigger

#

Going to the bottom left they stick out a little bit more each box

#

bottom right*

nimble lava
#

it's 2 pixels off per side of a box apparently

#

lines up now

#

but

#

I can't scale a 2 pixel issue down

#

best I can do is use half the original size and add 1 to the box size from the looks of it

#

:/

agile moss
#

Is that the ancient game?

nimble lava
#

y

agile moss
#

Nice. I should probably shut up, because this is off-topic and I don't have anything useful to say. Would love to see this in #303934982764625920 later though

nimble lava
#

if i make it work eventually lol

half latch
#

So your boxes are 52 wide now ?

nimble lava
#

no, since the original is off 2 per box

#

I can at best use half the size and adjust by 1

#

so I got roughly 86 pixels per side

#

roughly cause I'm dropping 1/3 a pixel per box to make it an integer

half latch
#

Can you send me the background image ? Want to try if I can do anything better

nimble lava
#

sure

tight bear
#

Seems as if lines and images are overlapping, which could make it tricky to line up nicely.

#

But if tiles were placed with a small pixel gap between each other where the line could be drawn, that's as perfect as you can get.

nimble lava
#

this is the one without lines. Not sure if the gap you mean is there

desert sapphire
#

Where is it from?

tight bear
#

Are you drawing 2 lines now?

nimble lava
#

no, the lines I am drawing on top is for me to know where to place the pieces

#

basically

#

I am making the game for a forum so a guy gave me the image to work with

tight bear
#

It looks really good though, so the gap doesn't really matter.

#

But imagine placing a bunch of 50x50 images next to each other. Each image would occupy 0-49, 50-99, etc

#

Meaning wherever you'd draw a single line, it'd be overlapping one edge, which is slightly off center still

#

In which case you could align tiles with a (box_size + 1) gap so that lines are never overlapping tiles. 0-49, 50, 51-100, 101, 102...

desert sapphire
#

Is the right side on the original image even a full square?

nimble lava
#

can't tell you for sure tbh. I can only assume they are supposed to be. but since the width/12 + 2 align with the background lines on the original

#

I can only say no

#

is there a point in leaving a gap if there is none in the original tho?

tight bear
#

As long as it looks good with the lines.

#

When it comes to making sure your tiles are squares, just check the size of the image? I assume they're scaled down in game?

desert sapphire
#

The problem seems to be that you are dividing it in perfect squares while the last element is a rectangle

#

also the bottom row

nimble lava
#

the ratio works for the amount of squares

#

its 12 wide and 9 high, 2048/12*9 is my height of 1536

#

issue is probably what Grote meant.

tight bear
#

Your screenshot says otherwise.

#

As in, the edges aren't looking like squares.

half latch
#

They are all 172*172

#

except the last ones

nimble lava
#

did you count or what

#

xD

tight bear
#

Well, 172*12 = 2064, not 2048

half latch
#

The last one of each row is 156*172

nimble lava
#

how did you figure that out btw

half latch
#

And the last one of each column is 172*160

#

GIMP with the square selection tool

tight bear
#

In your code, what have you set box_size to?

nimble lava
#

basically width/12 + 2 for the 2048 one

#

or +1 for the 1024

#

so I was assuming squares, yes

tight bear
#

How about we do this the other way around.

half latch
#

Now you have the dimensions, it should be easier ^^

tight bear
#

Set a fixed box_size, since your tiles should be fixed size, then you calculate the window size from that.

#

2048 isn't divisable by 12.

nimble lava
#

y my approx is 170 cause i convert to int then +2 to match
How do I map my pic onto the calculated window size tho. If I just stretch to fit it won't line up right just the same

tight bear
#

Could you send one of the tile images?

nimble lava
#

it's one big one. I suppose I'd have to crop out one tile and make my own

#

actually, that's prolly what I should be doing

tight bear
#

That would easier to manage, and saves processing time as well.

#

Make sure each tile image is a specific square size you've given it, which you can then use to calculate distances in the game.

nimble lava
#

but loading one big image into the background should be faster than 6 smaller ones to make the big one, no?

tight bear
#

That's true. You could still keep your images in one spritesheet, just as long as the size is correct.

#

I assume you're using subsurface or whatnot to extract each tile.

nimble lava
#

in all honesty, I was just gonna crop out one of the paper tiles in gimp and paste them onto the bottom and right edge

#

so I'd have an image that works

#

I'm not building the image tile for tile but I was just using the whole thing as one background image and refreshing each tick. Probably a bit cruder than you imagined ^^,

tight bear
#

Oooh, it's really just one large image at the moment?

desert sapphire
#

These had the lines in code put on top of them.

tight bear
#

Oh, and the original image already has lines drawn on top.

nimble lava
#

yes

tight bear
#

Aight sorry, figured you were playing around with the actual tiles.

nimble lava
#

I wish. Then the different size wouldn't have happened

tight bear
#

But then it might just be the original image that isn't perfectly square at the end.

nimble lava
#

which is why I am in gimp right now. To finally fix that issue ^^

sinful oasis
#

Hey i'm trying to figure out how to place labels when a button is pressed. The issue is that the placed labels are on top of each other and they have no variables linked to it

#

i tried using a variable x but it doesn't work at all

#

(forgot to mention i'm using tkinter)

nimble lava
#

are you using pack/place/grid?

sinful oasis
#

grid

nimble lava
#

are you keeping track of button presses to vary column and/or row of each label?

sinful oasis
#

nope

nimble lava
#

well then you are just pasting them over each other. Grid widgets need separate placements. So you want a variable that increases with each press or call of your create label function and use that to vary your placement of the label

#

so you use a global variable inside the function that makes your labels

#

define like x = 0 in your main or just below your imports and put global x right below your function def, if you use x in the declaration after that, you are referencing the one outside the call. So if you add 1 that means that addition gets saved even after the function ends.

sinful oasis
#

what i'd like to do is when button is pressed create a label in row=3 bound to a variable, if pressed again label in row=4,again bound, row=5 etc..

nimble lava
#

can you paste or snap your button code here?

sinful oasis
#
 boutonvalidation = Button(mainframe, text="Ajouter",command=lambda: self.spellencooldown(tkvar.get(), tkvar2.get()))

#
def spellencooldown(self,perso, spell):
       Label(mainframe, text=spell).grid(row=x, column=1)
nimble lava
#

you are referencing an x that has no value

sinful oasis
#

that is the rest of my tries

#

with x

nimble lava
#

what you want is something like

    def spellencooldown(self, perso, spell):
        global x
        Label(mainframe, text=spell).grid(row=x, column=1)
        x += 1
sinful oasis
#

what i did before is define x=3 (row=1,2 are used) then x+= 1 after label is created

#

here is my code

#

i defined x=3 defore the class

desert sapphire
#

Why don't you make x part of the class?

#

with self.x

nimble lava
#

that works too y

#

mine is less elegant

sinful oasis
#

i do self.x = 3 then use it ?

nimble lava
#

then you end up redefining it as 3 every call

sinful oasis
#

how do i get around it ?

#

Ok got it working now how do i create a new variable each time ?

#

For the label

#

d["labelspell{0}".format(x)]

#

i saw this as a solution

#

but i'm not sure

desert sapphire
#

What variable needs to be created every time?

sinful oasis
#

a variable linked to the label that gets created

nimble lava
#

I thought you only wanted to put the labels next to each other

desert sapphire
#

Is it bound to the command?

sinful oasis
#

the label creation ?

desert sapphire
#

The var for the label, is that the label itself, or a value for the command of the label?

sinful oasis
#

label * l itself so that i can edit it

desert sapphire
#

I can think of something.
What kind of data will be in this variable and how would it change?

sinful oasis
#

The label itself is just for display purpose but his coordinates will be used to delete the line. The line would be composed of Nameofspell,cooldown. I am gonna make a button that will tick down the cooldown(so i have to edit this label) and if the cooldown=0 then delete the line

desert sapphire
#

When you use a Stringvar you can edit that and the text on the label will change.

sinful oasis
#

How do i use it (sorry i'm a newbie) ?

#

i mean

desert sapphire
#
variable = StringVar()
Label(root, textvariable=variable)
variable.set("This is the text of the Label")```
sinful oasis
#

aaaaaaaaaaaaaaah

#

i'll have to create multiple variable to modify the text ?

desert sapphire
#

One stringvar per label you want to change

sinful oasis
#

But i won't have a finite number of labels

desert sapphire
#

How are you keeping track of your labels?

sinful oasis
#

I'm going to make a picture to explain

#

The user chooses a character and a spell then adds it to the cooldown"list"

#

just missing the cooldown label that will be next to "Spellname that will be in cooldown" the button to tick down the cooldown

desert sapphire
#

They'll have to be saved at some place in the code, a dictionary peprhaps

sinful oasis
#

llike this d["labelspell{0}".format(x)]

desert sapphire
#

Something like that yes. Depends a bit on what things need to be saved.

#

So it needs to be at least the name of the cooldown label

sinful oasis
#

Just the cooldown Label is enough

#

Sorry if I'm not c'ear enough

desert sapphire
#

There should also be a cooldown time saved or not?

sinful oasis
#

Yes

#

There should be

#

(sorry fro the response time had to take care of smth)

desert sapphire
#

Don't worry.

#

I'm cooking diner right now.

#

I quickly put this togheter as an example of a countdown.

#
from tkinter import StringVar, Tk, Frame, Label, Button

root = Tk()

spells = {}
spells["Leviosa!"] = {
    "title": StringVar(),
    "default_cooldown": 2000,
    "cd_duration": StringVar(),
    "cooldown": 0
}

spells["Leviosa!"]["label"] = Button(
    root, textvariable=spells["Leviosa!"]["title"], command=lambda: activate(spells["Leviosa!"]))
spells["Leviosa!"]["title"].set("Leviosa!")
spells["Leviosa!"]["label"].pack()
Label(root, textvariable=spells["Leviosa!"]["cd_duration"]).pack()


def activate(spell):
    spell["cooldown"] = spell["default_cooldown"]
    spell["cd_duration"].set(spell["cooldown"])
    root.after(100, countdown, spell, 100)


def countdown(spell, reduction):
    spell["cooldown"] -= reduction
    spell["cd_duration"].set(spell["cooldown"])
    if spell["cooldown"] > 0:
        root.after(100, countdown, spell, 100)


root.mainloop()
proper glade
#

im trying to draw a tiny triangle in a 16x16 pixmap with QPainter

#

just... why

#

both of those lines have the same length and in theory should look exactly the same but flipped horizontally

#

but for some reason qpainter doesn't draw lines consistently

desert sapphire
#

16 has no middle

proper glade
#

ive tried using a qpainterpath too, and a polygon

#

@desert sapphire left one draws from bottom left to 7, 0, right one draws from bottom right to 8, 0

sinful oasis
#

will try this but pretty sure it's gonna work thanbks !

proper glade
#

๐Ÿคท

sudden coral
#

@proper glade Did you ever solve that? I'm just curious as to what the solution was.

proper glade
#

@sudden coral i ended up using good old bresenham to plot the points manually

#

looks like qt's line drawing algorithm isn't too great

sudden coral
#

Bah, lame

proper glade
#

unfortunately this means missing out on antialiasing, since painter.drawPoint doesn't take care of that

sudden coral
#

That's just another thing for you to re-implement yourself ๐Ÿ˜„

proper glade
sudden coral
#

I was under the impression you didn't want AA anyways

proper glade
#

i had it on at first and the triangle looked wonky

#

so i turned it off to see what the deal is

#

and lo and behold it's wonky all the way down

sudden coral
#

That skimage function looks promising

proper glade
#

here's hoping ๐Ÿ˜„

proper glade
#

nope, the skimage functions are weird too

proper glade
mighty frigate
#

noice

#

@proper glade what did you use ?

#

also you have a lot of fingers

proper glade
#

@mighty frigate

    pixmap = qt.QPixmap(14, 15)
    pixmap.fill(qt.Qt.transparent)
    painter = qt.QPainter()
    painter.begin(pixmap)
    
    painter.setPen(qt.QColor(255, 255, 255, 255 * .1))
    for x, y in zip(*line(0, 14, 7, 0)):
        for iy in range(y):
            painter.drawPoint(x, iy)
            painter.drawPoint(14-x-1, iy)
            
    for x, y, alpha in zip(*line_aa(0, 14, 7, 0)):
        painter.setPen(qt.QColor(255, 255, 255, 255*alpha*.1))
        painter.drawPoint(x, y)
        painter.drawPoint(14-(x+1), y)

    painter.end()
    
    up_arrow_pixmap = pixmap
    down_arrow_pixmap = pixmap.transformed(qt.QTransform().scale(1, -1))
#

i ended up combining the two of them

mighty frigate
#

noiceยฒ

proper glade
#

and instead of drawing both lines i drew one and reflected the points on the other side

mighty frigate
#

dem your drawn it yourself ??

proper glade
#

more-or-less ๐Ÿ˜›

#

scikit deserves a lot of credit though

#

i have no idea how to implement antialiasing

mighty frigate
#

soo

#

I guess, all the click catching, etc is done by hand too ?

proper glade
#

oh, nah, all of those are pushbuttons

mighty frigate
#

aaaaaah

proper glade
#

their pixmaps are cached too

mighty frigate
#

you scared me

#

okok

proper glade
#

lol no need to reinvent the wheel there ๐Ÿ˜›

mighty frigate
#

some people are just angry ya know

#

is this like

#

a digital music box ? :p

proper glade
#

it's a step sequencer primarily intended for programming drums

mighty frigate
#

that's neat

proper glade
#

it's heavily based off of the one in FL Studio

mighty frigate
#

all in python ?

proper glade
#

yep

mighty frigate
#

what about the perf ?

#

looks good

proper glade
#

gotta be cause I want to integrate it with another DAW that has python scripting capabilities

#

the performance is alright so far

mighty frigate
#

okay

sinful oasis
#

hey ๐Ÿ˜ƒ i am using tkinter and i want to have a button on the bottom of my frame, the issue is that i am using grid and i cannot enter row or column because i have labels that my code add each button press

#

i figured ou t a way around but i want to make sure there is no other way (my "fix" is to remove the button each time a new label appears and place the button one row lower etc..)

mighty frigate
#

I'm making progress

serene spoke
azure bolt
#

Im trying to present data exactly like in the picture, but in a tkinter window. Whats the best way of doing so?

azure bolt
#

Its pretty much stock data, thats all packed into an array. Curious if anyone has any suggestions

serene spoke
#

Oh my. I wasn't aware that Tkinter couldn't load a font from a file. Hmmmm

trim rapids
#

Can someone tell me how they would go about stacking a frame on top of a frame in tkinter?

#

@ me if you know

serene spoke
#

@trim rapids as I understand it, you can't

trim rapids
#

damn alright thanks @serene spoke

trim rapids
#

Is there a way to remove all widgets in one command

#

Instead of .grid_remove each widget

#

@ me if you have an answer

serene spoke
#

@trim rapids no

nimble lava
#

nvm

mighty frigate
#

Hey everyone, I have a weird problem with Qt, using QLineEdit

#

here's a sample of my problem


from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *

import sys

app = QApplication(sys.argv)

edit = QLineEdit()
window_type = Qt.WindowType.Tool|Qt.WindowType.FramelessWindowHint|Qt.WindowType.WindowStaysOnTopHint
edit.setWindowFlags(window_type) # comment this line and everything is working
edit.show()

QObject.connect(edit, SIGNAL('editingFinished()'), edit, SLOT('deleteLater()'))
QObject.connect(edit, SIGNAL('editingFinished()'), app, SLOT('quit()'))

QTimer.singleShot(500, edit, SLOT('setFocus()'))

app.exec_()
#

the goal is to create a "free" (as in without parents) lineedit, and set the focus on it

#

I've tried things, but it looks like it can't be done with those special windows flags I'm setting

#

any idea ?

nimble lava
#

anyone able to troubleshoot with me? I don't understand why the movement in case of an event is this wonky despite it working just fine outside of my event loop

#

the lower part just makes the first piece go to every set of coordinates I defined as a tile, which works just fine
but my event movement just goes bananas for some reason

mighty frigate
#

(I "solved" my problem... rather than making a parentless lineedit, I added it to the app scene (which is an openGL scene). A bit tedious but it's working)

manic lodge
#

how do i get the time since it was first run

karmic shoal
#

you could use the datetime module to get the time as soon as you launch the app, then along the road you can calculate the time difference

sinful oasis
#

@karmic shoal are you familiar with tkinter ?

#

@karmic shoal are you familiar with tkinter ?

#

because i need to send the row of a button when pressing the button and i can't figure it out

karmic shoal
#

what have you tried so far?

sinful oasis
#

in the command part i tried lambda c=self.x:fucntiontobecalled(c)

#

tried to put the row in a list but i can't get the position of the good row

karmic shoal
#

can you post your code?

sinful oasis
#

Yes

manic lodge
#

Right, trying to use datetime in pygame

karmic shoal
#

@manic lodge your question was how do i get the time since it was first run

manic lodge
#

Yes, i can do that in pygame right?

#

Or are u saying theres an easier way in pygame

karmic shoal
#

I'm not familiar with pygame

manic lodge
#

Ok no worries

#

So, how do i get the current time?

#

tried datetime.now()

karmic shoal
#

does that not work?

#

!e

from datetime import datetime
print(datetime.now())
proven basinBOT
#

@karmic shoal Your eval job has completed.

2019-03-20 14:04:17.459775
manic lodge
#

No, needed datetime.datetime.now()

#

Right, ok!

sinful oasis
#

Any ideas @karmic shoal

karmic shoal
#

well I'm looking at it, and can't you pass whatever row you use when calling grid to the function in the lambda when binding the button?

sinful oasis
#

I can pass it but the variable changes each time (self. x +=1)