#user-interfaces

1 messages · Page 55 of 1

eager beacon
#

hmmm

unique forge
#

ok

#

interesting

eager beacon
#

yes very

#

the only difference is one is a negative number

unique forge
#

I wonder what the problem is

#

btw who is your profile pic

eager beacon
#

the girl from the baby got back music video

#

so

#

lets think about the error

#

What are the rules for performing a sqrt

unique forge
#

?

#

math.sqrt finds the square root of a number

eager beacon
#

okay, whats the sqrt of 3

unique forge
#

1.7320508075688772

eager beacon
#

how about -3

unique forge
#

that closes the app

eager beacon
#

hmm

#

so what do you think the problem is?

unique forge
#

im not sure

#

does float include negative numbers

eager beacon
#

yes a float can be negative

unique forge
#

ok

#

then I'm not sure

eager beacon
#

you cant find the square root of a negative number because

#

so what could you do to ensure the number is never negative

unique forge
#

maybe dont allow the - sign

#

how do you program that

eager beacon
#

well no

#

the problem is in square root

#

if the smaller number is on the left hand side then the number will be negative

unique forge
#

well you cant square root a negative number

#

it wont be correct

#

im forgetting my math class I took just a month ago

eager beacon
#

okay

#

math_a = math.sqrt(abs(c2**2 - b1**2))

#

abs is absolute value

unique forge
#

ok

#

thank you

#

it works!

#

how long have you been doing python

eager beacon
#

since 2.5 was released

#

whenever that was

unique forge
#

2008

#

wow

eager beacon
#

sounds right

unique forge
#

thats almost my my whole life

unique forge
#

@eager beacon How do I program a button to clear text in a QLineEdit

eager beacon
#

clicked.connect(le.clear)

unique forge
#

ok thanks

#

is this correct

#
self.ui.lineEdit.clear
eager beacon
#

you need to put it in connect but it should work

unique forge
#

oh

eager beacon
#

you did ask how to do it with a button press

unique forge
#

I didnt put it in the connect

#

I put it in a

#
def clrsqr(self):
eager beacon
#

are you doing anything else in that method?

unique forge
#

I want each button to clear multiple LineEdits

eager beacon
#

b1.clicked.connect(le.clear)
b1.clicked.connect(le2.clear)

#

either way it does the same thing

unique forge
#

yep

#

it works

#

just wanted to try save time

eager beacon
#

just wanted you to know you could have more than one connected slot

unique forge
#

@eager beacon does the icon work on a different computer

#

if it doesnt will the icon work if stored on a ftp or http server

eager beacon
#

ya know, i've never tried

#

but assuming you can mount the drive on your machine it should work

unique forge
#

ok

#

is there other ways to do the icon

eager beacon
#

I have to ask why you would want something like that though

#

and what do you mean other ways

#

whats the goal

unique forge
#

another way to have a app icon

#

my goal is to have a nice app icon

eager beacon
#

how you are setting it won't effect how it appears

unique forge
#

I just want to be able to see the icon on other computers

eager beacon
#

well then you need to read up on pyrcc

digital rose
#

So, I ended up dragging an image instead of trying to design my own labels and buttons. Is there way to take a picture and then shade in the fields from the PNG I got from the internet. Basically, I want to fill in the empty holes with a black dot when the user progresses a level. Or should I go about designing my own custom stuff?

unique forge
#

@eager beacon how do I convert my app into a .exe file

eager beacon
#

you'd have to find a tutorial somewhere and follow it.

#

its more trouble than its worth for simple apps

unique forge
#

ok

timid ether
#

How can I make my QMainWindow automatically fit to QTableWidget, so that they both scale when I drag them bigger from the corner?

#

as in QTableWidget covers all of the MainWindow except border

half shuttle
#

Hey I'm looking to help contribute to some open source work, are there any projects that need graphic design help?

whole dagger
#

@timid ether do you have a layout for your qmainwindow?

eager beacon
#

@timid ether set a centralWidget in the main window and set a layout on the widget. then add the table to the widgets layout

silver monolith
#

guys I want to ask one question, can we add multiple GUI windows using tkinter like there is base windows with 3 menudriven options and then after click anyone of them each can open in an seperate new window???

modern marsh
#

guys I want to ask one question, can we add multiple GUI windows using tkinter like there is base windows with 3 menudriven options and then after click anyone of them each can open in an seperate new window???
@silver monolith yup

#

i do it all the time

#

@silver monolith do you want help?

#

ping me if you do

safe egret
#

Hi guys, I'm trying to run tkinter but it won't show up

inner nest
#

try something more like this (you forget to run the application mainloop):
if __name__ == '__main__': app = Application() app.mainloop()

safe egret
#

I managed to fix it... added self.win instead of just win

#

and also the win.mainloop() I placed it in init

leaden tiger
#

hello, i am trying to create a new window in my programm by

def function(variable):
    newWindow = Toplevel(root)
    newlabel = Label(newWindow,text="Hello")
    newLabel.pack()

the window shows up, but there is no label with "hello"?

inner nest
#

where are you allocate root ?

leaden tiger
#

root is outside

#

interesting is that
Label(newWindow,text="Hello").pack
works

oak portal
#

Do ya'll know some way to change a label's entire background?

#

In tkinter

#

Forgot to specify that

#

bg and background only change the text background GWchadThonkery

#

Well, figured somewhat of a workaround

#

root.tk_setPalette("color")

#

Now I can remove backgrounds from the other stuff

modern marsh
#

hello, i am trying to create a new window in my programm by

def function(variable):
    newWindow = Toplevel(root)
    newlabel = Label(newWindow,text="Hello")
    newLabel.pack()

the window shows up, but there is no label with "hello"?
@leaden tiger you did not use mainloop()

leaden tiger
#

@modern marsh after newLabel.pack() -> root.mainloop()?

modern marsh
#

uhh

#
def function(variable):
    newWindow = Toplevel(root)
    newlabel = Label(newWindow,text="Hello")
    newLabel.pack()
    newWindow.mainloop()
#

i guess

#

never used TopLevel

#

i always make new Tk windows

unique forge
#

Hi

#

I was using QT Designer and QT creator to create a app

#

I was using Pycharm but it kept giving this error

#
ImportError: DLL load failed: The specified module could not be found.
#

so I switched to Mu and finished programming the rest of the app

#

the error is now haunting me again

#

I want to convert the app to a .exe file so I used pyinstaller

#

each time I open the .exe it gives this error

#
ImportError: DLL load failed: The specified module could not be found.
#

please help!

leaden tiger
#

@modern marsh yes this works now ... thank you very much! 🙂

modern marsh
#

:))

#

happy to help

unique forge
#

hello?

lyric nebula
#

tkinter

inner nest
#

you can use ttkthemes templates

lyric nebula
#

whats that?

lyric nebula
#

oki

#

how do i use them

#

wait i looked at the example, let me try it

inner nest
#

yes, I was about to say that

lyric nebula
#

lol

#

the thing is, it didnt make a difference :<

#

is it because i am using a background image

pure cloak
#

does pyqt5 work with 3.7

lyric nebula
#

o0k i figured it out, works now

static cove
#

@pure cloak It should, yes

pure cloak
#

i have designed my ui in pyqt, i cant convert it into python though

bronze basin
pure cloak
#

ok

static cove
pure cloak
#

Okay

#

pyuic5 inpt.ui -o output.py
this is a cmd command right

#

@bronze basin

bronze basin
#

yes

pure cloak
#

i tried it but when i run the code nothing opens

#

it looks to have converted properly and there arent any errors

bronze basin
#

your running the raw file ?

pure cloak
#

yes

#

it has been a while since i used uis

#

import sys
from PyQt5 import QtCore, QtGui, uic

from file import *
 
class MyWindowClass(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)

i need to run this code right

#
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()
#

and this

#

or something similar

unique forge
#

    app = QtWidgets.QApplication(sys.argv)
    MyWindow = MainWindow()
    MyWindow.show()
    sys.exit(app.exec_())
#

try this

pure cloak
#

i am still confused as to why the auto file isnt working

unique forge
#

thats what I had in the bottom of my QT5 application

pure cloak
#

yeah

#

i found the correct code

#
import sys
from PyQt5 import QtWidgets, uic

from spam_auto import Ui_MainWindow


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, obj=None, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

app = QtWidgets.QApplication(sys.argv)

window = MainWindow()
window.show()
app.exec()

this is my code

Traceback (most recent call last):
  File "C:\Users\aksha\Desktop\spamApp\spam_mod.py", line 4, in <module>
    from spam_auto import Ui_MainWindow
ImportError: cannot import name 'Ui_MainWindow' from 'spam_auto' (C:\Users\insertNameHere\Desktop\spamApp\spam_auto.py)
>>> 

this is my error

static cove
#

@pure cloak is your UI_MainWindow a .ui file or a .py file?

silent cedar
#
import keyword
from tkinter import END

def highlight(text):
    keywords = keyword.kwlist
    for kw in keywords:
        text.tag_remove(kw, 1.0, END)
        first = 1.0

        while True:
            first = text.search(
                kw, first,
                nocase=False,
                stopindex=END
            )

            if first == "":
                break

            first = float(first)

            last = first + len(kw)

            text.tag_add(kw, first, last)
            first = last
            
        text.tag_config(
            kw,
            foreground="#aa71eb"
        )```

Hi, I have the following code for syntax hightlighting
#

given the following text hello this is a test open works too lmao lol lal lol

#

it marks is is a test open works too lmao lol lal lol purple

#

but it should only mark is

#

any ideas how to solve the issue?

pure cloak
#

@pure cloak is your UI_MainWindow a .ui file or a .py file?
@static cove a .py file

#

nvm got the issue

#

noice, it works

#

just curious, is there any documentation for pyqt5

static cove
#

There are two places for documentation

silent cedar
#

Ping me when answered

stray jackal
#

Yoda - ping me when answerd you have ( sounds yodaish )

brittle hull
#

Hi, I'm ploting some data on pyqtgraph and the x-data format is timestamp. Is there an easy way to display the x-axis data in another format?

static cove
#

is the timestamp in epoch by chance?

brittle hull
#

Yes (needs to be divided by 1000 as it also contains thousandth of a second)

static cove
#

Check out DateAxis then, it's a feature within pyqtgraphs that will auto-format epoch timestamps very nicely

#

I found some decent documentation somewhere, let me see if I can find it again

brittle hull
#

Thanks @static cove !!!!

silent cedar
#

Oh I see now

#

If the character is 2 characters long its adding 2 to 1.0 and thats 3.0

#

But obviously in tkinter the character numbers are a bit different

#

How would I fix that and when do tkinter characters start at 2.0 ?

pure cloak
#

I have a question, what is the syntax for calling a function when a button is clicked in pyqt5

#

the pyqt 4 syntax below doesnt work

self.beeMovie.clicked.connect(self.bee)
bronze basin
#

@pure cloak should work

#

unless your using a ui file

#

then its self.ui.button.clicked.connect(self.function)

pure cloak
#

No, i am using a py file

bronze basin
#

did u convert the ui file to a py file

pure cloak
#
raceback (most recent call last):
  File "C:\Users\me\Desktop\spamApp\spam_mod.py", line 40, in <module>
    window = MainWindow()
  File "C:\Users\mr\Desktop\spamApp\spam_mod.py", line 25, in __init__
    self.beeMovie.clicked.connect(bee)
UnboundLocalError: local variable 'bee' referenced before assignment
#

yeah

bronze basin
#

yeah then you have to use self.ui

#

like i said

#

not self.

pure cloak
#

ok

pure cloak
#

Main window has no attribute ui

#

that is the error it gives

#
Traceback (most recent call last):
  File "C:\Users\a\Desktop\spamApp\spam_mod.py", line 40, in <module>
    window = MainWindow()
  File "C:\Users\a\Desktop\spamApp\spam_mod.py", line 25, in __init__
    self.ui.beeMovie.clicked.connect(self.bee)
AttributeError: 'MainWindow' object has no attribute 'ui'
>>> 
pure cloak
#
import sys
from PyQt5 import QtWidgets, uic
import pyautogui
from time import sleep
from spam_auto import Ui_Spammy
import tkinter

def spam(fileSpam,wait):
    file=open(fileSpam, mode='r')
    time.sleep(wait)
    for word in file:
         pyautogui.write(word)
         pyautogui.press('enter')



class MainWindow(QtWidgets.QMainWindow, Ui_Spammy):
    def __init__(self, *args, obj=None, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

        self.mode="beeMovie"
        self.file=""

        self.ui.beeMovie.clicked.connect(self.bee)


        def bee(self):
            print('barry')






        

app = QtWidgets.QApplication(sys.argv)

window = MainWindow()
window.show()
app.exec()

this is my entire code if it helps

bronze basin
#

@pure cloak

#

add the code above self.setupUi(self)

#
self.ui = Ui_mainwindow()
pure cloak
#

Ui_MainWindow has no attribute Button

#

that is the error i am getting now

#

this is so many errors

#

im gonna go to a help channel

silent cedar
#
def highlight(text):
    keywords = keyword.kwlist
    for kw in keywords:
        text.tag_remove(kw, 1.0, END)
        first = 1.0

        while True:
            first = text.search(
                kw, first,
                nocase=False,
                stopindex=END
            )

            if first is None or first == "":
                break
            
            first_splitted = first.split(".")
            if len(first_splitted) == 1:
                break

            last = f"{first_splitted[0]}.{int(first_splitted[1]) + len(kw)}"

            character_before_first = text.get(f"{first_splitted[0]}.{int(first_splitted[1]) - 1}")
            last_splitted = last.split(".")
            character_after_last = text.get(f"{last_splitted[0]}.{int(last_splitted[1]) + 1}")

            if character_before_first != " " and character_after_last != " ":
                break

            text.tag_add(kw, first, last)
            first = last
            
        text.tag_config(
            kw,
            foreground="#aa71eb"
        )``` ok I managed to fix it but now if I have the following string:

`hello this is a test open works too lmao lol lal lol` its not marking anything but it should mark `is`
#

any idea on how to fix it? I have no clue why this doesnt work as this is only checking if the found string is not a substring

#

^^ it should not mark the is in this

past locust
#

hello all. im stuck with an exasperating isssue. i disabled a key with -> "return 'break'" but now the key seems to be permanently disabled. any ideas how to fix that? btw im using tkinter.

eager beacon
#

really?

#

how did you disable the key?

past locust
#

in a separate function, which just said return break

#

after that, im not able to activate the key again

#

its quite exasperating

eager beacon
#

so your button press connected to a function that returned break?

past locust
#

yes

eager beacon
#

thats not even valid syntax

past locust
#

thats supposed to disable a key in tkinter

eager beacon
#

post your code please

true wolf
#

Can I show image in tkinter without Pillow ?

safe vapor
#

Is it possible to add a right click contex menu to all Entry and ScrolledText widgets (Select All, cut, copy, paste)?

past locust
#

@true wolf yes, you can draw images using the canvas

#

@safe vapor heres what i came up with:-
`
import tkinter
from tkinter import *

root = Tk()

text = Label(root, text ="test this right click menu..",
width = 50, height = 30)
text.pack()

m = Menu(root, tearoff = 0)
m.add_command(label ="Cut")
m.add_command(label ="Copy")
m.add_command(label ="Paste")
m.add_command(label ="Reload")
m.add_separator()
m.add_command(label ="Rename")

def popup(e):
try:
m.tk_popup(e.x_root, e.y_root)
finally:
m.grab_release()

text.bind("<Button-3>", popup)

root.mainloop()
`

#

@safe vapor i hope it helps ☝️

hazy sandal
#

Hey ! So im currently doing a Image Visualizer as project because im curious and I want to increase my python coding skill. I really like to use the less libs possible and I was wondering if it was possible to create kinda like JFrame in python without any libs ?

eager beacon
#

do you mean external libs?

#

there is a built in gui library called tkinter but I highly suggest you use pyqt or pyside2

true wolf
#

@true wolf yes, you can draw images using the canvas
@past locust i wanted to use cv2

eager beacon
#

@past locust I know you like a challenge but most people just want to get their project built

past locust
#

@true wolf cv2? Thats kinda weird. Why would you use cv when you have ton of canvas functions built in

safe vapor
#

@past locust That only creates a box for a single widget. i need to override the Entry class e.g.

class cEntry(Entry):
    def __init__(self, master, value="", **kw):
        Entry.__init__(*(self, master), **kw)
        self.m = Menu(Entry, tearoff=0)
        self.m.add_command(label="Cut")
        self.m.add_command(label="Copy")
        self.m.add_command(label="Paste")
        Entry.bind("<Button-3>", self.do_popup)
    def do_popup(self, event):
        try:
            self.m.tk_popup(event.x_root, event.y_root)
        finally:
            self.m.grab_release()

The issue is i keep getting Entry has no attribute 'tk'

type object 'Entry' has no attribute 'tk', <class 'AttributeError'>, type object 'Entry' has no attribute 'tk',   File "G:\My Drive\projects\myproject\script.py", line 6222, in login_window
    user = cEntry(uframe)
  File "G:\My Drive\projects\myproject\script.py", line 84, in __init__
    self.m = Menu(Entry, tearoff=0)
  File "C:\Python38-32\lib\tkinter\__init__.py", line 3272, in __init__
    Widget.__init__(self, master, 'menu', cnf, kw)
  File "C:\Python38-32\lib\tkinter\__init__.py", line 2561, in __init__
    BaseWidget._setup(self, master, cnf)
  File "C:\Python38-32\lib\tkinter\__init__.py", line 2530, in _setup
    self.tk = master.tk
past locust
#

Oh

#

Can we head to dms?

safe vapor
#

sure

digital rose
#

#!/usr/bin/env python3

-- coding: ascii --

import sys, os, time, datetime, signal

"""
The configuration file for runner.py will contain one line for each program that is to be run. Each line has the following parts:

timespec program-path parameters

where program-path is a full path name of a program to run and the specified time(s), parameters are the parameters for the program,
timespec is the specification of the time that the program should be run.

The timespec has the following format:

[every|on day[,day...]] at HHMM[,HHMM] run

Square brackets mean the term is optional, vertical bar means alternative, three dots means repeated.

Examples:

every Tuesday at 1100 run /bin/echo hello
every tuesday at 11am run "echo hello"
on Tuesday at 1100 run /bin/echo hello
on the next tuesday only, at 11am run "echo hello"
every Monday,Wednesday,Friday at 0900,1200,1500 run /home/bob/myscript.sh
every monday, wednesday and friday at 9am, noon and 3pm run myscript.sh
at 0900,1200 run /home/bob/myprog
runs /home/bob/myprog every day at 9am and noon

"""

open the configuration file and read the lines,

check for errors

build a list of "run" records that specifies a time and program to run

define up the function to catch the USR1 signal and print run records

sort run records by time

take the next record off the list and wait for the time, then run the program

add a record to the "result" list

if this was an "every" record", add an adjusted record to the "run" list

repeat until no more to records on the "run" list, then exit

past locust
#

@digital rose can u please elaborate upon what youwish to make

digital rose
#

it is a python deamon code

past locust
#

U mean daemon?

digital rose
#

yes

eager beacon
#

dude this is user interfaces

#

go to unix or devops if you need help with something like that

#

or just sit in a help channel long enough for someone who can answer your question to answer

past locust
#

@digital rose I can understand. But making an app of that sort is a bit complex. I suggest you go for some video tutorials

unique forge
#

@eager beacon do you know the answer to my problem? #help-grapes

past locust
#

@silent cedar I just went thruthru your code. This method isnt gonna help much. I suggest you know about lexers and tokens, using Pygments module with tkinter

#

A decent example

pure cloak
#
from tkinter import filedialog
file=filedialog.askopenfilename(initialdir="/",title="Open File",filetypes=("Text Files","*.txt*"))
print(self.file)

this is the error

dialog.py", line 43, in show
    s = w.tk.call(self.command, *w._options(self.options))
_tkinter.TclError: bad file type "*.txt*", should be "typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?"
>>> 
past locust
#

Have you tried making a window first?

#

Theres the syntax:

#

askopenfilename(filetypes=(("Template files", "*.tplate"), ("HTML files", "*.html;*.htm"), ("All files", "*.*") ))

#

filetypes=(("Text Files",".txt"))

#

@pure cloak

pure cloak
#

okay

past locust
#

Each filetype is given as a tuple inside of parentheses

pure cloak
#

isnt this the same

#

oh

past locust
#

No

pure cloak
#

okay

past locust
#

👍

pure cloak
#

it works but i only want .txt files

#

it is only accepting .tplate

#

How do i do that

past locust
#

Ill have to look at it

pure cloak
#

anything would help

#

i am almost done with a project i have been working on for a while

#

yess, i got it

past locust
#

Solved?

silent cedar
#

@past locust hey, I already fixed it with passing in the regexp kwarg (setting it to True) and changing the search to rf"\m{kw}\M"

past locust
#

Ah

#

@pure cloak so your prob was solved?

pure cloak
#

Yeah

#

Thanks

#

tho i want to stop the kivy window from opening

#

only the file dialog

#

if it is possible

past locust
#

Why is the kivy windows opening?

#

Have u included some kivy code too? @pure cloak

pure cloak
#

no

#

i use pyqt

#

and when i click a button it opens the file dialog

#

but fr some reason it opens a kivy window when i open the file dialog

past locust
#

Thats a weird bug

#

Can u dm methe whole code

pure cloak
#

sure

#

done

finite swallow
#

I had a question.Can I somehow use electron and python for making apps?and if yes then is it feasible to do so or not?

silk basin
#

Sorry to interrupt, is anyone here familiar with QSettings within PyQt5?

rocky dragon
#

What issues are you having?

silk basin
#

I am currently creating a reminder system that allows a user to set reminders. I have it working when the program is open. User can actively add reminders to a drop down. The issue is when I close the program all data is lost.
I wanted to use QSettings to set up a group called:

settings.begindGroup("Reminders")

then add my reminder class which holds:

        self.key = key #Key for QSettings
        self.sort_key = sort #Key for sortings reminder in correct order. (Composed of the date/time)
        self.date = date #Date the reminder is set for
        self.time = time #Time the reminder is set for
        self.title = title #Title of the reminder
        self.description = description #Description of the reminder

How do I go about adding now these values to the settings for each individual reminder? is it just:

  reminder_node = Reminder(milliseconds,sort_key_string,         selected_date, hour_cb.text(), title.text(), description.text())

  settings.setValue(reminder_node.key, reminder_node)
rocky dragon
#

It won't be able to properly serialize and deserialize your object (not sure if it's customizable in the python interface). You can use something like json and dump/load info from there as strings in the QSettings object, or just skip the QSettings

silk basin
#

Well my group has already used QSettings and set it up.
I can access the QSettings with

self.app.settings.etc.

is there a better way of doing this ? @rocky dragon

eager beacon
#

probably sqlite3

#

@silk basin

#

or actually tinyDB could be a good fit

dim meteor
#

Hey guys, i'm looking to do a gui for one of the automation i've made but i don't know which library to use.

I would like something where i can use html/css/react because i know my way around these techs.

From what i've seen Electron could be a good solution but if you have any other libs would you be kind enough to share them with me 🙂

plush stream
#

Hey, is there any way to change pyqt theme in real time?

leaden tiger
#

hello, i have a question regarding a card game in tkinter... is it possible if you have an interface, that the computer plays out card automatically without doing or clicking something?

eager beacon
#

@plush stream what do you mean by theme?

plush stream
#

Like dark theme

eager beacon
#

have you tried changing the current app palette?

plush stream
#

Yes i tried the palette.setColor() and it worked, but i have problem making it changing in real time

eager beacon
#

what was the trigger?

plush stream
#

I tried with button

eager beacon
#

did you try to use setPalette after setColor

plush stream
#

Yes

eager beacon
#

I've never tried setting a palette like that before but I've used stylesheets and sometimes after setting the stylesheet you need to call update() on the widget for it to register

#

you might try that with your palette

plush stream
#

Oh nvm, got it to work

#

Turns out i forgot to call the function, lmao

eager beacon
#

haha

past locust
#

@leaden tiger yes you can do it, without having to click the card

#

@leaden tiger heres something:-

Suppose you have a window named root, and you can call a function called after()

This function does something after a specified time(in ms).
Yoi can say : root.after(2000,do_something)

#

2000 milliseconds, and do_something is a function you would want to call after 2000 milliseconds

past locust
#

Or 2 seconds in general

silver monolith
#

hey

#

is there any way to fix it

#

here's the code

#
from tkinter import *

root = Tk()
input_of_values = Entry(root)


calculate_label = Label(root, text="Standard calculator - :)")

# Label for all the numbers from 0 to 9

num_0 = Button(root, text="0")
num_1 = Button(root, text="1")
num_2 = Button(root, text="2")
num_3 = Button(root, text="3")
num_4 = Button(root, text="4")
num_5 = Button(root, text="5")
num_6 = Button(root, text="6")
num_7 = Button(root, text="7")
num_8 = Button(root, text="8")
num_9 = Button(root, text="9")

# displaying statements
calculate_label.grid(row=0, column=0)

# displaying the console to get user input
# displaying the numbers

num_0.grid(row=8, column=0)
num_1.grid(row=7, column=0)
num_2.grid(row=7, column=1)
num_3.grid(row=7, column=2)
num_4.grid(row=6, column=0)
num_5.grid(row=6, column=1)
num_6.grid(row=6, column=2)
num_7.grid(row=5, column=0)
num_8.grid(row=5, column=1)
num_9.grid(row=5, column=2)


# end
root.mainloop()
#

I am really a beginner to GUI stuff

silver monolith
#

ohh I missed columnspan

#

its working now

past locust
#

@silver monolith u just dont use grid() to place widgets. its an inefficient method, and quite exasperating too. Instead i suggest you use the .place() or .pack() method. But the best would be .place(x=10,y=10) as you can place at specific coordinates

hexed anchor
#
@bot.event
async def on_ready():
    await bot.change_presence(status = discord.Status.idle,activity = discord.Activity(type=discord.ActivityType.listening, name="People's answer to if they want to play a game"))
    class Application(tk.Frame):
        def __init__(self, master=None):
            super().__init__(master)
            self.master = master
            self.pack()
            self.create_widgets()
            self.bot = bot
            self.discord = discord

        async def create_widgets(self):
            self.hi_there = tk.Button(self)
            self.hi_there["text"] = "The bot is ready"
            self.hi_there.pack(side="top")

            self.quit = tk.Button(self, text="QUIT", fg="red",command= await shutdown())
            self.quit.pack(side="bottom")

        async def shutdown(ctx):
            await self.bot.change_presence(status = discord.Status.offline)
            await ctx.send("Shutting down!")
            await ctx.bot.logout()

    root = tk.Tk()
    app = Application(master=root)
    app.mainloop()```
The problem is that it is giving me RuntimeWarning and idk what to do because this is the first time that i am working with tkinter and implementing into a discord bot, as you can see the idea is simple, i want to the bot to shutdown when i press the quit button. Any help/guidance is appreciated. 😄
past locust
#

So u just want to close the application when u press the button?

hexed anchor
#

yes

past locust
#

Oj

#

So here it us

hexed anchor
#

not the application, the discord bot...

past locust
#

Yeah thats embedded into the tk window right?

#

So all u want to do is close the window?

hexed anchor
#

uhh... no?

#

So all u want to do is close the window?
@past locust not just close the window, shutdown the bot too...

past locust
#

Oh

hexed anchor
#

am i posting my problem in the right channel?

past locust
#

Yes ofc

hexed anchor
#

ok great.. so any guidance on how i should handle it?

#
@bot.command(aliases = ['quit'])
@commands.has_permissions(administrator=True)
async def shutdown(ctx):
    await bot.change_presence(status = discord.Status.offline)
    await ctx.send("Shutting down!")
    await ctx.bot.logout()
    print("Logged out :)")

This is the shutdown command that comes later in the code of the bot, if u were wondering...

past locust
#

`
def close():
global root
root.destroy()

write code to quit your bot

root=Tk()
But=Button(root,text="shutdown", command=close)
But.pack(side=TOP)
root.mainloop()
`

hexed anchor
#

so no need to create a class?

past locust
#

So what do u think?

#

No ofc

hexed anchor
#

ohhh, ok i will try this method. Thanks a lot.

past locust
#

The place where ive written write code to quit your bot,ut just put in the codr to quit the bot

#

Simple

hexed anchor
#

ok got it

past locust
#

👍

leaden tiger
#

@past locust thank you i will try it!

past locust
#

Yeah sure 👍

#

In the method I told you, yoi just replace 2000 with however chancr time u want to give the player

#

Untile the computer plays its move

hexed anchor
#

just getting something clear, the command doesn't get executed until u press it right?

hexed anchor
#

.....

pure cloak
#

lol

past locust
#

@hexed anchor I couldnt get you.

hexed anchor
#

i meant... its working just some errors...

#

first i did the mistake of calling the shutdown function when i passed it into the Button attribute

#

but now

#
@bot.event
async def on_ready():
    await bot.change_presence(status = discord.Status.idle,activity = discord.Activity(type=discord.ActivityType.listening, name="People's answer to if they want to play a game"))
    async def shutdown():
        await bot.change_presence(status = discord.Status.offline)
        await bot.logout()

    loop = asyncio.new_event_loop()
    root = tk.Tk()
    Shutdown_button = tk.Button(root,text = "Shutdown",command = shutdown)
    Shutdown_button.pack(side="top")
    root.mainloop()``` This is what my code looks like now. I get the GUI when i run it but when i click the shutdown button, it gives me this error- ```C:\Users\User\AppData\Local\Continuum\anaconda3\lib\tkinter\__init__.py:1283: RuntimeWarning: coroutine 'on_ready.<locals>.shutdown' was never awaited
  self.tk.mainloop(n)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
past locust
#

Go on

hexed anchor
#

as far i can see, it has some problem with awaiting something and i dont understand what it is. What am i doing wrong here?

past locust
#

Why do u want to use await?

hexed anchor
#

uhh.. that is the only way i can turn off the bot... 🤷‍♂️

past locust
#

Theres a much easier replacement fot await

#

U just wanna tell the program to wait a bit right?

#

Before closing?

hexed anchor
#

no no, i want it to close instantly when i click the shutdown button

past locust
#

Oh

#

Why have u put await then

hexed anchor
#

wait wdym

past locust
#

Awaits task is to wait vefore executing tge given command

hexed anchor
#

hmmm.. and that is the only i can logout from the discord bot so... ig i have no choice but to use it 🤷‍♂️

past locust
#

Hmm

hexed anchor
#

i even tried adding loop = asyncio.new_event_loop() loop.run_until_complete(shutdown)

#
@bot.event
async def on_ready():
    await bot.change_presence(status = discord.Status.idle,activity = discord.Activity(type=discord.ActivityType.listening, name="People's answer to if they want to play a game"))
    async def shutdown():
        await bot.change_presence(status = discord.Status.offline)
        await bot.logout()

    loop = asyncio.new_event_loop()
    root = tk.Tk()
    Shutdown_button = tk.Button(root,text = "Shutdown",command = loop.run_until_complete(shutdown))
    Shutdown_button.pack(side="top")
    root.mainloop()``` Ok this is the new code and now when i try to run it, the error is- ```C:\Users\User\AppData\Local\Continuum\anaconda3\lib\tkinter\__init__.py:1283: RuntimeWarning: coroutine 'on_ready.<locals>.shutdown' was never awaited
  self.tk.mainloop(n)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Tcl_AsyncDelete: async handler deleted by the wrong thread```
past locust
#

Ah

hexed anchor
#

so u got whats wrong?

past locust
#

The prev code was correct

#

U cant add in loop as a command

hexed anchor
#

but it was still throwing the error... 🤷‍♂️

past locust
#

It takes in event functions, not var names associated with commands

#

Ill see it

hexed anchor
#

ok i am back to my previous code and back to square 1 of the errors- C:\Users\User\AppData\Local\Continuum\anaconda3\lib\tkinter\__init__.py:1283: RuntimeWarning: coroutine 'on_ready.<locals>.shutdown' was never awaited self.tk.mainloop(n) RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

🤦‍♂️

past locust
#

Oh

#

Ill try to see wait

hexed anchor
#

kk, i will wait...

past locust
#

I suppose it has nothing to do with tkinter, but keyword placement

#

Because the button is doing everything alright, but there seems to be some error with the shutdown func

hexed anchor
#

but when i use it as a simple command, it works perfectly fine... it must be some incompatibility with the tkinter..

past locust
#

I couldn't get u

#

Tkinter gas nothing to handle with passing bot logout commands. It just passes them onto the compiler, and thereafter handled by the compiler itself

hexed anchor
#

i mean the commands and the problem mostly seems to be there because its an async function

#

if it was just a simple command then i wouldnt have so problem calling it

past locust
#

hmm

#

why dont u try using a simple def?

#

i still dont get why ur trying to implement coroutines in your bot

hexed anchor
#

just to make life easier? lol

past locust
#

lol no. just for the sake of realising whats the prob

hexed anchor
#

ok i just tried adding the simple exit(0) and it doesnt work too

#
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Continuum\anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "discord bot.py", line 12, in exit
    exit()
  File "discord bot.py", line 12, in exit
    exit()
  File "discord bot.py", line 12, in exit
    exit()
  [Previous line repeated 984 more times]
RecursionError: maximum recursion depth exceeded```
past locust
#

u just say exit()

#

not exit(0)

#

it doesnt take any args

#

or u can use quit() too

#

without passing any args

#

done?

eager beacon
#

exit and quit are only for the repl

#

use sys.exit() if its a script

past locust
#

@hexed anchor yes. you will need to use sys.exit() as exit() and quit() will be dependant on the site module in python and hence are considered bad.

#

they just raise a SystemExit exception

#

and sys.exit() is much better

hexed anchor
#

ok

past locust
#

Did you program work?

hexed anchor
#

oh i have class rn so imma test it later...

past locust
#

Yeah sure

dim meteor
#

Hey guys, i'm looking to do a gui for one of the automation i've made but i don't know which library to use.

I would like something where i can use html/css/react because i know my way around these techs.

From what i've seen Electron could be a good solution but if you have any other libs would you be kind enough to share them with me 🙂
@dim meteor

charred fractal
#

react native?

#

@dim meteor

dim meteor
#

Can i implement react native with python tho ?

charred fractal
#

no

#

but you cant use react with python

#

they're 2 different languages

#

you could use a flask server or sum'

#

and a node server as a reciever

dim meteor
#

Yea i could try that

#

So i would need to build an api in python and make call to it with react native right ?

charred fractal
#

well yes, tho react native itself doesn't have a server receiver, you have to use node modules or sum' for that

dim meteor
#

Thanks for ur help. Going to try to implement that 😃

charred fractal
past locust
#

@dim meteor tkinter or pyqt? undoubtedly the best GUI frameworks in python

#

easy to use

#

just a lil time to learn. highly dynamic, flexible. u can really do wonders with this

dim meteor
#

I have already use qt but in c++, is it pretty much the same ?

past locust
#

yeah

#

almost all functions have same names

#

its pyqt5 in python

#

but tkinter is easier than any other framework in this world

charred fractal
#

ngl tho, tkinter isn't as good for a nice GUI

dim meteor
#

yea, the issue i have with those framework is that it's really hard to make something that looks really good

past locust
#

it is easy

charred fractal
#

tkinter < qt < html/css

#

from the 3 mentioned

past locust
#

and if u want easy and good looking frameworks at the same time, especially in python, tkinter/pyqt5 are the best choices tbh

#

otherwise JS is the best for good looking guis

charred fractal
#

in terms of ease, i'd say tkinter is pretty much the most simple, but it looks awful, qt, not as simple as tkinter (IMO), but can look pretty ok, HTML/CSS/JS least simple (with python), but highest value in design

past locust
#

some good looking gui 👇

#

and this

#

how else do u define something good looking?

#

just that u will need to add in some extra effort

charred fractal
#

have you looked at the qt.io page?

#

thats good looking for example

#

the 2 above are very... developer-y

past locust
#

well, @dim meteor , i think its your choice, in the end. but i will say that, if u just wanna get your work done, then dont worry bout good or bad looking. but if u do worry, then just put in some extra efforts

charred fractal
#

well...

#

if they want to have the thing running first and foremost, and later make it look good, having a very devy-looking GUI at first, and building on that aint the greatest of choices

dim meteor
#

how else do u define something good looking?
@past locust discord ui is a great example, clean, nice color palette, good dynamic elements without doing too much

#

Because, imo the 2 gui you uploaded are not good looking for me

charred fractal
#

yeah, they're very developer-like

#

while discord is user-like

dim meteor
#

yup

hexed anchor
#

@past locust i tried the sys.exit but didnt get good results. the bot just quits down after i run it.. 🤷‍♂️

past locust
#

u need to add sys.exit() in the shutdown command

silent cedar
#

Hey
Im trying to make a find and replace function supporting regex. Now, in the find function Im checking if the toggle button for regex is turned on. Somehow its always False, even though I set it to True when its being clicked on.
code: https://hastebin.com/aquvatojel.py

past locust
#

is this the whole code

#

?

silent cedar
#

thats the code for the find and replace function

#

yea

past locust
#

ah

#

do u mind sharing the whole code?

silent cedar
#

the code of the whole project?

past locust
#

yes

silent cedar
#

uh, that's much code, though I can provide a bit context if needed

past locust
#

yeah thatll be enough

silent cedar
#

self.text is Text object

past locust
#

hmm

#

can i share my find and replace function? i made it like 4 years ago

silent cedar
#

if you want

#

it does mark characters if I type something like 74 and the example string is 748

#

then it would mark 74

#

but for example [0-9]+ it wouldn't mark anything even when regex is turned on

charred fractal
#

if your example string is 748 and the regex is [0-9]+ thats correct tho

silent cedar
#

it is

#

it should mark 748

#

but it doesn't

charred fractal
#

cause 748 are all in the range 0 to 9

silent cedar
#

ye

charred fractal
#

do you mind showing what you're looking at when you mean that?

#

it marks

silent cedar
#

it adds a tag and changes the background color of the characters yellow-ish

charred fractal
#

can you show?

#

a screenshot with the above

#

regex [0-9]+
test (whatever you want, tho it should be numbers and alpha chars)

silent cedar
#

as you see, it doesn't mark anything

charred fractal
#

is regex a global variable?

silent cedar
#

its in a function which is in another function

#
def fun():
  def fun():
    regex = False
    def fun():
      ...```
charred fractal
#

cause for toggling you're checking if the text of that button for regex is Regex Off, but you're not checking what regex is

#

cause you're reassigning and stuff, but...

#

when you call find_and_replace, you're setting regex to False

silent cedar
#

yes

charred fractal
#

the state is never kept

silent cedar
#

I dont understand

charred fractal
#

you're calling the toggle function

#

and set the button text

#

but the variable regex isn't kept

past locust
#

Yoda i sent u my sample code

silent cedar
#

how can I change that tho

#

global the variable?

past locust
#

Yoda u need not go all into nested funcs

#

its always a bit hard to keep up with

#

u can try running my sample code

charred fractal
#

well, for debugging purposes, just print regex, or stop your debugger in the toggle function

silent cedar
#

print it when

charred fractal
#
            def toggle():
                print(regex)
                if toggle_button.config("text")[-1] == "Regex Off":
                    toggle_button.config(text="Regex On")
                    regex = True
                else:
                    toggle_button.config(text="Regex Off")
                    regex = False

right after

silent cedar
#

local variable 'regex' referenced before assignment

charred fractal
#

unbound

#

yes

silent cedar
#

yes

charred fractal
#

when you assign regex, you're creating an entirely new variable

#

you're not reassigning/updating your desired variable

silent cedar
#
def toggle():
                global regex
                if toggle_button.config("text")[-1] == "Regex Off":
                    toggle_button.config(text="Regex On")
                    regex = True
                else:
                    toggle_button.config(text="Regex Off")
                    regex = False``` then
charred fractal
#

but if regex isn't on the global scope, (which it doesn't seem to be) it wont work correctly either

silent cedar
#

wym

#

it works now

#

thank you

#

I also globalled the variable in the other nested function

#

find

#

and ty 8bit as well

charred fractal
silent cedar
#

well now it says regex is not defined in find

#

🤔

charred fractal
#

did you actually make it a global variable (also, since it seems you're using a class, why not do self.regex and put the initial value in the constructor?)

silent cedar
#
if regex:
NameError: name 'regex' is not defined```
#

yes I did

#

I will try setting it as self attribute

#

yup, works again, thx

normal plinth
#

Are there any pros and cons for using MySQL with PYQT5 instead of the built in p5 sql connector?

pearl dragon
#

is there a tool you guys would suggest using to making a python ui

#

or would you just suggest PySimpleGUI

unique forge
#

Tkinter

#

or PQT5

#

@pearl dragon

#

two best programs to create Python GUI's

#

Tkinter is built in to python, so all you have to do is

#
from tkinter import *
pearl dragon
#

oh ok thanks alot dude

unique forge
#

but PyQT5

#

has a software called QT Designer

#

which allows you to create drag and drop GUI's

#

but yo still have to program the buttons and wisgets after

silver monolith
#

hey guys will you suggest me the best way (resource) to learn Tkinter

silent cedar
#
g = tokenize(BytesIO(text.get(1.0, END).encode('utf-8')).readline)

    try:
        for token in g:
            if token.type == 3:
                text.tag_add(
                    token.string,
                    f"{token.start[0]}.{token.start[1]}",
                    f"{token.end[0]}.{token.end[0]}"
                )

                text.tag_config(
                    token.string,
                    foreground="#fcba03"
                )

    except TokenError:
        pass``` Hey why is this not working? It's not highlighting the string
#

example:
print("hello")

It should highlight "hello" (with the quotes) in #fcba03

#

but it doesn't highlight it at all

past locust
silver monolith
#

that's the one I am seeing

#

lol

past locust
#

Lol ohk

silver monolith
#

just on the calculator part

past locust
#

U can learn from the tkinter docs too

silver monolith
#

1 hr or so

#

U can learn from the tkinter docs too
@past locust yeah

past locust
#

Tkinter docs have everything

silver monolith
#

hmm

dusky blaze
#

tkinter isn't a program.

leaden tiger
#

hello,
i have a logic question in tkinter
i define objects and buttons on startup, but i need to assign them in a function later on ... now i get the following error:
UnboundLocalError: local variable 'playerTwoCard1' referenced before assignment
is the only solution to set those variables at the beginning of the code and set them to None?

digital rose
#
    def __init__(self, parent):
        super().__init__(parent)
        self.quit = Button(self, text="Quit", padx=20, pady=5, command=self.parent.quit)
gui = TempConvertor(root)

AttributeError: 'TempConvertor' object has no attribute 'parent'

#

Whats wrong here

static cove
#

You probably want to save a reference to the parent
self.parent = parent

digital rose
#

Yeah

#

I just realised I found it later in the code, dunno how it ended up there; but I brought it back to its original position.

#

So all good

#

thanks

digital rose
#
self.create_widgets()
self.f_scl = Scale(self, variable=self.fahr, to=500, from_=-100, commands=self.refresh, length=400,
                           orient=HORIZONTAL)
gui = TempConvertor(root)

_tkinter.TclError: unknown option "-commands"

#

@static cove yeah sorry for the ping, but since you're the only one active here can you help me with this please?, and thanks.

static cove
#

Could you share more of your code? It's unclear what you're trying to do there

silent cedar
#

@digital rose it's command

digital rose
#

oh right

#

thanks

sleek pier
#

hi

static cove
#

@sleek pier you're creating the Entry widget and packing it in one line. That's bad practice as .pack() doesn't return anything. You want to initialize it and then on a separate line pack it, that way e retains the reference to the Entry widget

dusk rover
#

Hello. I am trying to create an app that uses python to get the sensor data from the sensor and display this information in graph form to the user. Right now, I have created a website that takes the image and displays it to the user and that works for the basic purpose.
I would like my app to be able to control the fan speed and so on. I was wondering for a newbie what would be the fastest way to get this app done?
I want app to write my app in a future proof way thats why I am asking

amber kraken
#

Hey does anyone know how to have text of a ui update without user input?

sleek pier
#

@sleek pier you're creating the Entry widget and packing it in one line. That's bad practice as .pack() doesn't return anything. You want to initialize it and then on a separate line pack it, that way e retains the reference to the Entry widget
@static cove Thanks!

real parcel
#

a question for anyone who uses wxPython: is there any downside to creating and storing stuff like wx.Menu instances in your wx.App? this is a small example of what i mean
https://pastebin.com/xd0RTVFG

#

my thinking is it doesn't make sense to store stuff like menus inside window/panel/etc instances

digital rose
#

How easy tkinter 1 to 10 guys

proven oxide
#

easy enough to get u into python guis.

digital rose
#

easy enough to get u into python guis.
@proven oxide I found them easy and my aim to make alot of projects using tkinter gui

proven oxide
#

i suggest using another thing for big big projects but tkinter is fine..good luck!

digital rose
#

Yeah ik what u mean but we can't just disrespect tkinter like that because he our boi right.

proven oxide
#

tkinter is very good..if ur aiming for very modern uis then tkinter isnt the best

digital rose
#

Tkinter is the stepping stone of kivy

proven oxide
#

i havent tried kivy

#

i tried qt and tkinter

#

they are both good and positive experience

digital rose
#

I need to try qt

proven oxide
#

qt is great

digital rose
#

I know oop

proven oxide
#

offers a lot

#

and also bit complex

digital rose
#

Qt only requires Oop right

#

Qt*

proven oxide
#

u can make ur whole text editor with it

#

syntax highlight tabs and everything

#

😍

digital rose
#

That is lovely

proven oxide
#

lol i love text editors

digital rose
#

Wow

#

U making me want to learn qt

proven oxide
#

most of times if i want to get into another language i create a bootleg text editor as a first project

#

so far i created one in java..node js and python

digital rose
#

Oh nice work

proven oxide
#

node js was modern but buggy...java didnt offered a lot and python was kinda perfect in some terms

digital rose
#

Yeah python work fine for anything because it's the way it build

proven oxide
#

python would be perfect if it wasnt slow

digital rose
#

Definitely

proven oxide
#

c and c++ kinda harsh

digital rose
#

But we can't expect to be perfect

proven oxide
#

these c langs offer u some gifts like speed and so..but hard work needed

#

we always want the best of the best..some have heavy disadvantages..some not

digital rose
#

C++ is tough I think I need alot of practice in python and JavaScript to order to even start the basic of c++

proven oxide
#

the only disadvantage soo far in c langs is being complex or too low but idk if thats a disadvantage

digital rose
#

The logic

proven oxide
#

javascript was easy to me..atleast and node js was even easier since its basically js

#

ppl love to hate js

#

but yet its really simple

digital rose
#

But as our brains grow through this adventures life in python and Java and JavaScript we will be able to understand c++ logic

proven oxide
#

moving from python to c++ can be a little bit strugglish

digital rose
#

Definitely

#

Even I struggled learning JavaScript syntax and stopped learning it and came back to python

#

It's because I wasn't ready then

proven oxide
#

js syntax is similar to c++

#

and java

#

but js itself is simple

digital rose
#

Now I'm ready to face anything

#

Because I worked with complex codes

#

And I make complex codes

proven oxide
#

how much experience

digital rose
#

Almost 2 years

proven oxide
#

my first hello world was years ago..and in multiple langs

#

my plans always messed up

#

i tried experiencing multiple langs and choosing from the best lol

digital rose
#

Lol

proven oxide
#

yet then just got attracted to art and did art for 4 years

#

i could've learnt in these 4 years

digital rose
#

I hate art

proven oxide
#

learnt code

digital rose
#

I failed art

proven oxide
#

digital art btw.

digital rose
#

Oh ok

#

😁

proven oxide
#

digital art can be tough just like or more than coding in some ways..but if u have tools and ur decided ur art type u can do fine in art

digital rose
#

Now just doing python challenges for logical thinking and problems solving

proven oxide
#

do projects

#

complex projects

#

challenges will improve problem solving i guess?

digital rose
#

Challenges definitely will improve thinking skills

proven oxide
#

good luck boi. i missed years and i gotta recover them since im still young

digital rose
#

Same

#

We still got Time

proven oxide
#

i did my very first hello world in lua i think.

#

first ever hello world

digital rose
#

Oh mine was python and still python and ending with something else

#

😁

proven oxide
#

anyways cya and also good luck.

#

been a good talk

digital rose
#

U too

wide ingot
#

does anyone here have experience with tkinter

hard bear
#

Hey fellas. What is the most basic and intuitive GUI tool in python? Like, I have made some analysis stuff in a python script, but it needs to be showed via some kind of GUI tool to demonstrate to my coworker, boss etc.
Any suggestion would be appreciated, thanks

waxen wadi
#

There's Tkinter

#

It's really easy to use

#

And default GUI for Python 3

digital rose
#

^

past locust
#

@hard bear tkinter's the best thing when u want to do something pretty much perfectly, and in a small amount of time.

#

its quite easy to learn

silver monolith
#

I am not ableto use the icon file on my tkinter app as an icon

normal plinth
#

Are there any pros and cons for using MySQL with PyQt5 instead of the built in mysql connector?

#

Ghul, I’m not very familiar but perhaps try a different file format for your image? Or are you missing an argument?

unique forge
#

@hard bear another option other than Tkinter is PYQT5 which has a drag and drop software called QT Designer

#

but you still have to program the widgets yourself

digital rose
#

b

silver monolith
#

Please someone help me out

digital rose
#

can anyone suggest some easy ways to make this chart interactive? e.g. you click a name and it shows text details of the architect and pictures of their work. either a javascript or codeless solution im thinking, maybe like flourish.studio.... not sure....

#

please @ me

wide ingot
#

@digital rose couldn't you just use a hyperlink attribute in html for each name

past locust
#

@digital rose yes there is. i can suggest a way, in which when you hover your mouse over the words, it shows info about them

#

you can use tkinter for this. easy. u just load in the image,and make something like this appear when u hover your mouse @digital rose

silver monolith
#

somone pinged me

#

?

#

I guess he/she deleted the message 😦

#

hey anyone know how to fix this issue
@silver monolith Is there anyone here who know a fix to this, I have tried png, ico, xbm format but still it is not working

#

do you guys think its becuase of my os, i.e manjaro

bronze basin
#

perhaps

mint ivy
#

how can I debug a rather huge pyqt application ? is there any specific tool or suggestions?

silver monolith
#

perhaps
@bronze basin do you think I should move back to windows

bronze basin
#

you can try it on windows?

#

perhaps if you dont want to move back you can just use a Virtual machine

#

and like have many environments

#

to test and program

silver monolith
#

I mean this project is an sort of college assingment and all of them have windows

bronze basin
#

not neccasarily

#

as i said

#

use a VM

silver monolith
#

my machine cannot hold vm

#

that's the problem

#

only 8gb ram

bronze basin
#

ah that is an issue

#

even if u do it will be very slow to the point

#

where

#

you will just not want to

silver monolith
#

yeah

bronze basin
#

i guess you can switch back to windows? especially if its an assignment or smth

silver monolith
#

yes

bronze basin
#

any help in google the problem?

#

maybe somebody

#

had the same issue or smth

silver monolith
#

ALL OF THE LINUX USERS HAVE THIS ISSUE

#

EVEN ON COMMERCIAL UBUNTU

bronze basin
#

interesting

silver monolith
#

sorry my caps got on

#

lol

bronze basin
#

np

eager beacon
#

@mint ivy breakpoints in pycharm?

silver monolith
#

what os are you on?

eager beacon
#

there are several ways to set an icon with tkinter

#

have you tried the others?

silver monolith
#

have you tried the others?
@eager beacon which others, using PhotoImage?

near kraken
#

ummguys i want to ethical hack can u help me?

silver monolith
#

I have tried and failed

near kraken
#

like send tutorial vids?

silver monolith
#

I am planning move back to windows

#

ummguys i want to ethical hack can u help me?
@near kraken go to #cybersecurity

near kraken
#

k tks

silver monolith
#

this is not the right channel

near kraken
#

sry

dense oasis
#

Anyone have any tips/tutorials for advanced tkinter interfaces (that look decent :P) or would it be best to move to something else if appearance matters?

bronze basin
#

PyQt

past locust
#

@dense oasis if u want decent looking stuff in tkinter, you will have to create custom functions to draw better looking graphics on the window. but if u just want to get the work done, pyqt5 is a good choice

dense oasis
#

So learning PyQt it is lol. Thanks a bunch to both of you!

silver monolith
#

finally did it

past locust
#

yeah anytime @dense oasis

deep hornet
#

hi

mint ivy
#

@eager beacon I should have used this from the very beginning !!!!!👍🏼👍🏼👍🏼

digital rose
#
        msg = QtWidgets.QMessageBox()    
        msg.setWindowTitle("Numeric Columns")
        msg.setText("Select the column to add to pie chart values")
        msg.setIcon(QtWidgets.QMessageBox.Question)
        msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Retry | QMessageBox.Ignore)
        self.my_vertical_layout = QHBoxLayout()
        column_int_types=([key for key in dict(df.dtypes) if dict(df.dtypes)[key] in ['float64', 'int64']])
        for cit in column_int_types:
            q_int_type = QtWidgets.QRadioButton(cit,self)
            self.my_vertical_layout.addWidget(q_int_type)
        x = msg.exec_()``` 
When the message popsup it does not include any radio button
eager beacon
#

you never added the new layout to the message box

#

you might just want to use a qdialog if you're going to mess with the layout anyhow

digital rose
#

@eager beacon can u edit n send the code please?

#

@wide onyx

eager beacon
#

I'm saying its not going to work how you want it to and that you should create your own

#

just use self.layout().addWidget(q_int_type) to see

mint ivy
#

I'm querying using psql in my app and want to show error pop up when ever the user chooses some parameters that there's no result for it.
the problem is in case of errors in querying my app crashes.
how can i handle them?

mint ivy
#

how can i make my application compatible with different resolutions?

still hedge
#

can i send the question here?

digital rose
#

Can I ask for help about tkinter here?

#

oh wait nvm my bad

stark cedar
#

the problem is that I can line-up the labels but I can't put the image next to the labels but not under them

mint ivy
#

@stark cedar you should first make a qhboxlayout first and then add the layout corresponding to each part

brisk sparrow
#

Hi

#

I am using panda3d

#

I need help on Onscreentext, I organize my code on a class and there I have missions, init, etc. I want to show to the user the missions he have but when I show a new missions appear this:

#

How I fix that?

vague gale
#
title_img = PhotoImage(file="title.png")
title_lbl = Label(app, image=title_img, bd=0, bg=app["bg"])
title_lbl.place(rely=.5, relx=.5, anchor="n")
title_lbl.grid(row=0, column=0)
#

how do i align it on the center?

wispy temple
#

title_lbl.pack(pady=20)
@vague gale

fluid tinsel
#

does the Curses module render the GUI on STDOUT?

loud kayak
#

where else would it go? it is the output.

fluid tinsel
#

like other modules makes a separate window?

past locust
#

@fluid tinsel almost all gui modules make a separate window. For example, Tkinter, PyQT5 etc

fluid tinsel
#

I’m talking about curses.

#

it seems to log the gui into STDOUT

#

like print

fallen rain
#

hi

#

can somebody pls help me?

#
root = tkinter.Tk()
root.title("Builder")


def get_default_values(datatype):
    data_type_dict = {"TIMESTAMPTZ":"CURRENT_TIMESTAMP"}
    values = data_type_dict.get(datatype)
    return values


BuilderName = Label(root, text="Record Builder", font="50").grid(row=0, column=0)
ColumnName = Label(root, text="Record Name").grid(row=1, column=0)
ColumnTypeName = Label(root, text="Record Type").grid(row=2, column=0)
DefaultTypeName = Label(root, text="Default").grid(row=3, column=0)

ColumnEntry = Entry(root, width=50)
ColumnDefaultEntry = Spinbox(root, values=(), width=48)
ColumnTypeEntry = Spinbox(root, values=("INTEGER", "TEXT", "BIGINT", "TIMESTAMP", "TIMESTAMPTZ"), width=48)

ColumnTypeEntry.grid(row=2, column=1)
ColumnEntry.grid(row=1, column=1)
ColumnDefaultEntry.grid(row=3, column=1)

root.mainloop()```
#

This is my code

#

This is how the GUI looks like

#

I want to implement the following idea

#

So the values for the spinbox which is next to the default label depends on the record type

#

like if the record type in Integer

#

the default value can be any integer

#

and if its text it can be any text

#

if the record type is datetime then the default can be CURRENT_TIMESTAMP

#

and also universally

#

a default value null can be set for any datatype

#

how can I change the values for the spinbox with respect to the record type?

#

pl ping me when help

#

thanks a lot!

inner nest
#

You can use a command and a textvariable in your spinbox to configure the values in the spinbox when someone insert a new value. @fallen rain

#
    if isinstance(record_name.get(), int):
      DaySpinBox.config(to=newvalues)

MySpinBox  = Spinbox(...,command=update_type)  ```
#

something like that maybe

fluid tinsel
#

is it possible to raise the text quality/resolution in tkinter?
I mean I know IDLE did it, but I can’t find where since there are around 500 files in that directory.

fallen rain
#

thanks @inner nest

sand pine
#

Noob here... for the life of me I can not find out how to get the output plot from sklearn's metrics.plot_confusion_matrix into a tkinter gui - can anyone point me to a reference?

inner nest
#

You can use Canvas @sand pine

digital rose
#

?

vague gale
#

how to change the size of a button?

#

i'm giving height=5 and this happens

modern marsh
#

the problem is that I can line-up the labels but I can't put the image next to the labels but not under them
@stark cedar use place() or grid() geometry managers

#

instead of pack()

#

for example:

#

image.place(x='5',y='7')

#

how to change the size of a button?
@vague gale use font attribute

#

or width attribute too

#

test them out

safe vapor
#

Im having an issue with:

ws = self.root.winfo_screenwidth() # width of the screen
hs = self.root.winfo_screenheight() # height of the screen
self.root.geometry("%sx%s+%s+%s" %(ws-100, hs-100, 50, 50))
self.root.update()
self.root.update_idletasks()

This is called after a login window which is cleared of all widgets and remade

children = self.root.winfo_children()
for child in children:
  child.pack_forget()
  child.destroy()

Its suppose to set it slightly smaller than the screen size and offset it from top left by 50 pixels.
When I run the code it works perfectly... when I freeze the code (cx_freeze) it keeps it in the same place as the login window (centred on screen) but does adjust the width and height.

dusk oriole
#

i am making a tkinter GUI app and i want to add a button that goes to a game i made in pygame, is there a way i can do that?

safe vapor
#

you can use the subprocess module:

import subprocess
f = open("output.txt", "w+")
subprocess.Popen([application_path], creationflags=8, shell=False, stdout=f, stdin=f, stderr=f) # you dont need to declare std args if it runs its own console or you dont need a console output.
#

creationflags=8 creates it as a new process, remove it to create it as a child process (if the main process quits then all child processes will quit)

obsidian moss
#

I want to embed my PyQt GUI in jupyter notebooks , but I'm having trouble finding any info at all about whether thats possible or how any notebook embedding is done (like how Plotly does it https://plotly.com/python/renderers/#interactive-renderers). Anyone know how to do that or what I should search to learn it?

Displaying Figures using Plotly's Python graphing library

fallen rain
#

How can I implement asyncio with tkinter?

#

pls help me

#

So I have a gui class

#
class SignUpModal:
    def __init__(self, master):
        self.master = master
        self.my_task = asyncio.Event()
        self.loop = asyncio.get_event_loop()```
#

like this

#

when a button is pressed on the tkinter window

#

this is the button

#
self.signup_button = Button(self.master, text="Sign Up", height=1, width=8, command=self.check_entries,
                                    relief=RAISED)```
#

this function is called

#
    def check_entries(self):
        manager = UserManager()
        try:
            self.check_credentials()
        except CannotSignUp as err:
            return self.show_warning(err)

        try:
            manager.create_user(username=self.UsernameEntry.get(), email=self.EmailEntry.get(),
                                password=self.PasswordEntry1.get())
        except asyncpg.UniqueViolationError:
            return self.show_warning("Credentials entered already exist")
        else:
            self.close_modal()```
#

at last the close_modal() func is called

#

this is the func

#
    def close_modal(self):
        self.master.destroy()
        self.done()
        print("done command called")```
#
    def done(self):
        self.my_task.set()

    async def wait_until_done(self):
        await self.my_task.wait()
        print(self.my_task.is_set())```
#

done basically sets the task

#

this gui thing is basically a signup gui

#

it looks like this

#

so now when the signup button is pressed

#

the asyncio event is set

#

In another file

#

(my main file)

#

I want to do this

#
loop = asyncio.get_event_loop()
root = tkinter.Tk()
newWindow = Toplevel(root, padx=10, pady=5)
newWindow.title("Sign Up")

rec_builder = login_modals.SignUpModal(newWindow)
rec_builder.show_modal()


async def logger():
    await rec_builder.wait_until_done()
    print("Sign up successful!")


try:
    loop.run_until_complete(logger())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()

root.mainloop()
#

So I want to wait for the event to be set

#

this is like a trigger to know whether the user is logged in or not

#

but I cannot do this because py try: loop.run_until_complete(logger()) finally: loop.run_until_complete(loop.shutdown_asyncgens()) loop.close() this blocks tkinter's mainloop

#

how to go about this?

#

any alternatives?

#

pls help

#

thanks!

#

pls ping me when help too

inner nest
#

Why do you need asyncio to check credentials ? You just have to add a function when you are pressing signup button and destroy the window when the user is connect (you can add a builtin tkinter messagebox to notify the user). @fallen rain

fallen rain
#

not to check

#

to know if user has finished signup

#

I have an event

#

@inner nest

vague gale
#

how do i change the column names in pyqt5?

eager beacon
#

@vague gale is that a tablewidget or tableview?

vague gale
#

tablewidget

eager beacon
#

setHorizontalHeaderLabels(["col1name","col2name"])

vague gale
#

thanks

mint ivy
#

do you have any reference about how to design a software? like how the flow of buttons and functions should be?

#

I'm making a software which is getting too much complicated and out of control and it's making me worried about future maintenance

vague gale
#

firstly you design the interface and then you start adding functionality to it

#

What are you using for making the software?

mint ivy
#

pyQt5

vague gale
#

I just started with it , it's pretty complicated for me to remember all these functions

#

probably because of the long names of them lmao

#

do you have experience with it?

mint ivy
#

yeah to some extent

#

haven't got the grip of the window Classes and the inheritance matters of it yet tho

vague gale
#

how do i use addButton function of QDialogButtonBox?

eager beacon
#

this might work, self.button_box.addButton(self.import_button,QDialogButtonBox.ApplyRole)

#

I'm not sure what role is best for something like Import

#

i guess QDialogButtonBox.ActionRole is more fitting

low dagger
#

What IDE is that?

vague gale
#

Python's IDLE LMAO

#

but I added a nice theme

eager beacon
#

IDLE...

#

why

vague gale
#

I just use it on the fly

#

When i'm too lazy to wait for PyCharm to open on my pc u_also_like_kotlin

eager beacon
#

but

#

its IDLE

vague gale
eager beacon
#

And I've timed every IDE/Editor and Sublime opens the fastest out of everything if thats what you're going for

lofty kernel
#
Your Sublime Free Trial Has Expired

Lol

modern marsh
#

Sublime has a trial !!

digital rose
#

in tkinter, is it possible to time.sleep() without the program showing that it's not responding?

eager beacon
#

you would be interrupting the event loop so I don't think so

digital rose
#

then, is it possible to track time without interrupting the event loop?

#

so if you press a button it tracks the time that is passing, and when it gets to 5 seconds or something it prints "Hello Youtube"

eager beacon
#

look at the functionroot.after

digital rose
#

it works! thanks!

digital rose
#

in tkinter, is it possible to create a variable root and assing it Tk() but without opening the window?

static cove
#

You can do something like root.withdraw() to have it not appear when you initialize it

digital rose
#

ok, but when i want to make it appear again? @static cove

#

with deiconify()?

static cove
#

I believe so, yes

tribal path
digital rose
#

Does anyone have any pointers on how I can go about making a web interface for a discord bot?

whole dagger
#

since you're asking here im assuming you want to use a python framework. Go with flask or django for the backend but you will need to use html/js/css for the front end. You also most likely need a database which the website share with the bot to keep all the changes then fetch the settings from the db via the discord bot.

ionic forge
#

hey guys how do we align buttons and labels in tkinter? i looked for it on the web but could not understand it!

#

my current window looks like this and i wanna work on beautifying it now!
ping me if you reply

inner nest
uncut pawn
#

I am trying to connect to files in python Tkinter together. One file has the main window after pressing a button u will enter the next file to the next window

ionic forge
#

@ionic forge your game_label was too large compared of your window size, use rows and columns values to fit at your design. eggs : https://paste.ofcode.org/M99gVXwi2LmshJ3KuedxJC
@inner nest
okay thanks! and is there any way to have empty rows/columns?

inner nest
#

I believe its not possible to have empty rows/columns. You can use padding to make spaces between items.

#

@ionic forge

ionic forge
#

okay! thanks

digital rose
#

so I am using flask to make a website and I need this if statement to work inside the html code but it does not want to work everything has been defined correctly as far as I am aware and yet it still does not work any help would be greatly appreciated thanks: [https://paste.pythondiscord.com/uyorunomor.xml] Line 24 {% if server.get('owner_id') == owner %}

#

in tkinter, is it possible to withdraw a window and then use after on that withdrawn window?

inner nest
#

@uncut pawn I don't fully understand where is your problème specifically but you can create a new window with toplevel() in a function and call it with a button if its what you are searching for.

#

@digital rose I think its the wrong Channel, I believe you are going to have more answers in #web-development

digital rose
#

i thought it would be here since it's html code but ill check it out

buoyant dagger
digital rose
#

Python's IDLE LMAO
@vague gale DARK THEME! i had it once lol

delicate latch
#

how can i move that entry right next to the Package Name label?

vague gale
#

@delicate latch use the move method 😂

modern marsh
#

use the geometry manager methods

#

like pack,place,grid

#

@delicate latch

median turtle
#

    def __init__(self, *args, **kwargs):
        super().__init__()

        self.setWindowTitle("My App")

        widget = QCheckBox()
        widget.setCheckState(Qt.Checked)

        widget.stateChanged.connect(self.show_state)

        self.setCentralWidget(widget)


    def show_state(self, s):
        print(s == Qt.Checked)
        print(s)```why does the s parameter print when self.show_state does not provide an argument? this is the result
#
0
True
2
False
0
True
2```
uncut pawn
#

@inner nest I want to have 2 files that have to different Tkinter WIndows if I press a button in the main window it will enter the second windows

inner nest
#

@uncut pawn ok, then try to use toplevel window like I said before

uncut pawn
#

k

clever lance
#
    def init(self):
        threading.Thread.init(self)
        self.daemon = True
        self.root = 0
        self.entry = 0
        self.label = 0
        self.button = 0
        self.timerValue = 0
        self.stopButton = 0
        self.start()

    def run(self) -> None:
        self.root = tk.Tk()

        # tkinter code goes here
        self.root.geometry("+2+0")
        self.root.config(background="black")

        self.label = tk.Label(self.root, bg="blue", fg="white", font=("Fixedsys", 28))
        self.entry = tk.Entry(self.root, bg="blue", fg="white", font=("Fixedsys", 28))
        self.stopTiden = tk.Button(self.root, bg = "black",fg = "grey", text = "Stop Spillet", command = self.stopTid)
        self.startTiden = tk.Button(self.root, bg = "black",fg="grey", text = "Start Spillet", command = self.startTid)

        self.startTiden.grid(row = 0, column = 1)
        self.stopTiden.grid(row = 0, column = 10)
        self.entry.grid(row = 1, column = 1)
        self.label.grid(row = 1, column = 10)

        self.root.bind("<KeyPress>",self.read,)
        self.root.mainloop()

    def read(self, event):
        key = event.keysym
        try:
            if key == "Return":
                self.getA()
                self.visTid()
        except:
            self.fejlTidvalg()


    def startTid(self):
        self.stopButton = 0

    def getA(self):
        self.timerValue = float(self.entry.get().format("%.2f",1.23456))
        print(self.timerValue)
        return self.timerValue

    def stopTid(self):
        self.stopButton = 1

    def visTid(self):
        self.label = self.label.config(text="Det her er timeren: {}".format(self.timerValue))

    def fejlTidvalg(self):
        self.label = self.label.config(text="FEJL -Vælg Venligst Et Tal")```

Not my entire code, my entire code is too long
#

Somehow label becomes a NoneType

  File "Tkinter2.py", line 57, in read
    self.visTid()
  File "Tkinter2.py", line 74, in visTid
    self.label = self.label.config(text="Det her er timeren: {}".format(self.timerValue))
AttributeError: 'NoneType' object has no attribute 'config'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "Tkinter2.py", line 59, in read
    self.fejlTidvalg()
  File "Tkinter2.py", line 77, in fejlTidvalg
    self.label = self.label.config(text="FEJL -Vælg Venligst Et Tal")
AttributeError: 'NoneType' object has no attribute 'config'```
#

please @ if any of you have a solution.

static cove
#

@clever lance .config() doesn't return anything, it completes the operation in place. So the line self.label = self.label.config(. . .) is actually overwriting self.label with None

clever lance
#

ah....

#

So can I do something ala "self.label = 0", "return self.label"?

#

or would that just set self.label to a 0, removing the text?

#

@static cove

static cove
#

If you just want to set the text there, it would be:
self.label.config(text="FEJL -Vælg Venligst Et Tal")
no assignment required

clever lance
#

Ahhhhh, I get it now. Alright, thank you very much for your time and help 🙂

mint ivy
#

@delicate latch Use form layout

buoyant dagger
#
import tkinter as tk


class GuiMain:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Testing classes with tkinter")
        self.window.minsize(1280, 720)

        self.main_frame = tk.Frame(master=self.window)
        self.main_frame.pack(fill=tk.BOTH, expand=1)

        self.top_frame = tk.Frame(master=self.main_frame, bg="#808080", height=360, bd=2, relief="solid")
        self.top_frame.pack(fill=tk.BOTH, expand=2, side="top")

        self.bot_frame = tk.Frame(master=self.main_frame, bg="#867979", height=300, bd=2, relief="solid")
        self.bot_frame.pack(fill=tk.BOTH, side="bottom", pady=(14, 0))

        self.window.mainloop()


GuiMain()

Is there anyway I can better organize this? I am planning to add a lot more and it will probably looked cluttered.

#

I was planning of making a menu that allows the user to switch "tabs". I was just wondering if I could make some object for each tab within this class.

obtuse acorn
#

I have two places in tkinter where a widget binds the parent to an even on left click in the init, the later ones always override the previous binding to the same event, is it possible to add bindings to the same event multiple times like

obj.bind(evt0, meth1)
obj.bind(evt0, meth2)
#

without overriding the first binding

orchid yoke
#

Can pywin32 check if window processes requires input or insertion of characters or if a certain window is clicked, then it's focus will stay on the window you clicked?

past locust
#

@obtuse acorn no. If you want to bind two functions to one event, you can call both functions in a separate function. Name it meth3.

#

`def meth1():
# someth
def meth2():
#somehing
def meth3(event):
meth1()
meth2()

bind em

obj.bind(evt0,meth3)
`

#

@obtuse acorn

modern marsh
#

can't lambda be used?

#

@past locust

past locust
#

No, not really.

#

The bind function takes two args, the event and the function

modern marsh
#

ok

#

guys how to install discord?

#

( i mean pip install)

silent cedar
#

pip install discord.py

modern marsh
#

anyone knows how to do exception handling?

#

nvm

small shadow
#

Hi, please look into my issue. 🙂 Appriciate it!

#

import requests
import json

#Internal modules
import constants

class WeatherAPI():

def get_weather(self):
    c = constants.constants().attributes()

    response = requests.get(c.attributes)
    data = json.loads(response.text)
    weather = (data['current']['weather'][0]['description'])
    return weather

def get_temp(self):
    c = constants.constants().attributes()

    response = requests.get(c.attributes)
    data = json.loads(response.text)
    temp = (data['current']['temp'])
    return temp
#

I get an: Exception has occurred: AttributeError
'str' object has no attribute 'attributes'

fluid tinsel
#

Hello, does the ‘curses’ module send the GUI as string to stdout/console with ANSI color codes, or does it create a new window normally?
It appears to send the GUI in the console.

slender lion
#

can sm1 help me with app development and stuff

#

where exactly to start learning kivy from

viral ridge
delicate latch