#user-interfaces
1 messages · Page 55 of 1
the girl from the baby got back music video
so
lets think about the error
What are the rules for performing a sqrt
okay, whats the sqrt of 3
1.7320508075688772
how about -3
that closes the app
yes a float can be negative
you cant find the square root of a negative number because
so what could you do to ensure the number is never negative
well no
the problem is in square root
if the smaller number is on the left hand side then the number will be negative
well you cant square root a negative number
it wont be correct
im forgetting my math class I took just a month ago
sounds right
thats almost my my whole life
@eager beacon How do I program a button to clear text in a QLineEdit
clicked.connect(le.clear)
you need to put it in connect but it should work
oh
you did ask how to do it with a button press
are you doing anything else in that method?
I want each button to clear multiple LineEdits
b1.clicked.connect(le.clear)
b1.clicked.connect(le2.clear)
either way it does the same thing
just wanted you to know you could have more than one connected slot
@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
ya know, i've never tried
but assuming you can mount the drive on your machine it should work
I have to ask why you would want something like that though
and what do you mean other ways
whats the goal
how you are setting it won't effect how it appears
I just want to be able to see the icon on other computers
well then you need to read up on pyrcc
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?
@eager beacon how do I convert my app into a .exe file
you'd have to find a tutorial somewhere and follow it.
its more trouble than its worth for simple apps
ok
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
Hey I'm looking to help contribute to some open source work, are there any projects that need graphic design help?
@timid ether do you have a layout for your qmainwindow?
@timid ether set a centralWidget in the main window and set a layout on the widget. then add the table to the widgets layout
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???
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
Hi guys, I'm trying to run tkinter but it won't show up
Is there anything that I missed?
I've called the class though
try something more like this (you forget to run the application mainloop):
if __name__ == '__main__': app = Application() app.mainloop()
I managed to fix it... added self.win instead of just win
and also the win.mainloop() I placed it in init
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"?
where are you allocate root ?
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 
Well, figured somewhat of a workaround
root.tk_setPalette("color")
Now I can remove backgrounds from the other stuff
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()
@modern marsh after newLabel.pack() -> root.mainloop()?
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
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!
@modern marsh yes this works now ... thank you very much! 🙂
hello?
you can use ttkthemes templates
whats that?
yes, I was about to say that
lol
the thing is, it didnt make a difference :<
is it because i am using a background image
does pyqt5 work with 3.7
o0k i figured it out, works now
@pure cloak It should, yes
i have designed my ui in pyqt, i cant convert it into python though
ok
I usually refer to this for different ways to load in/convert the .ui file https://www.learnpyqt.com/courses/qt-creator/first-steps-qt-creator/
yes
i tried it but when i run the code nothing opens
it looks to have converted properly and there arent any errors
your running the raw file ?
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
app = QtWidgets.QApplication(sys.argv)
MyWindow = MainWindow()
MyWindow.show()
sys.exit(app.exec_())
try this
i am still confused as to why the auto file isnt working
thats what I had in the bottom of my QT5 application
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
@pure cloak is your UI_MainWindow a .ui file or a .py file?
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 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
There are two places for documentation
There are the C++ docs, which is my go-to: https://doc.qt.io/qt-5/qtmodules.html
There are also the python docs, which are not as good as the C++ docs but if you aren't familiar with the C++ syntax, they'll be easier to understand: https://doc.qt.io/qtforpython/api.html
Ping me when answered
Yoda - ping me when answerd you have ( sounds yodaish )
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?
is the timestamp in epoch by chance?
Yes (needs to be divided by 1000 as it also contains thousandth of a second)
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
Slightly better documentation: https://pyqtgraph.readthedocs.io/en/latest/graphicsItems/dateaxisitem.html?highlight=Axis
Thanks @static cove !!!!
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 ?
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)
@pure cloak should work
unless your using a ui file
then its self.ui.button.clicked.connect(self.function)
No, i am using a py file
did u convert the ui file to a py file
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
i used pyuic5 input.ui -o output.py
ok
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'
>>>
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
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
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
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.
in a separate function, which just said return break
after that, im not able to activate the key again
its quite exasperating
so your button press connected to a function that returned break?
yes
thats not even valid syntax
thats supposed to disable a key in tkinter
post your code please
Can I show image in tkinter without Pillow ?
Is it possible to add a right click contex menu to all Entry and ScrolledText widgets (Select All, cut, copy, paste)?
@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 ☝️
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 ?
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 yes, you can draw images using the canvas
@past locust i wanted to use cv2
@past locust I know you like a challenge but most people just want to get their project built
@true wolf cv2? Thats kinda weird. Why would you use cv when you have ton of canvas functions built in
@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
sure
#!/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
@digital rose can u please elaborate upon what youwish to make
it is a python deamon code
U mean daemon?
yes
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
@digital rose I can understand. But making an app of that sort is a bit complex. I suggest you go for some video tutorials
@eager beacon do you know the answer to my problem? #help-grapes
@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
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 ...?}?"
>>>
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
okay
Each filetype is given as a tuple inside of parentheses
No
okay
👍
Ill have to look at it
anything would help
i am almost done with a project i have been working on for a while
yess, i got it
Solved?
@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"
Yeah
Thanks
tho i want to stop the kivy window from opening
only the file dialog
if it is possible
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
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?
Sorry to interrupt, is anyone here familiar with QSettings within PyQt5?
What issues are you having?
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)
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
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
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 🙂
Hey, is there any way to change pyqt theme in real time?
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?
@plush stream what do you mean by theme?
Like dark theme
have you tried changing the current app palette?
Yes i tried the palette.setColor() and it worked, but i have problem making it changing in real time
what was the trigger?
I tried with button
did you try to use setPalette after setColor
Yes
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
haha
@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
Or 2 seconds in general
hey
I am having this layout broken in between due to long text
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 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
@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. 😄
So u just want to close the application when u press the button?
yes
not the application, the discord bot...
Yeah thats embedded into the tk window right?
So all u want to do is close the window?
uhh... no?
So all u want to do is close the window?
@past locust not just close the window, shutdown the bot too...
Oh
am i posting my problem in the right channel?
Yes ofc
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...
`
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()
`
so no need to create a class?
ohhh, ok i will try this method. Thanks a lot.
The place where ive written write code to quit your bot,ut just put in the codr to quit the bot
Simple
ok got it
👍
@past locust thank you i will try it!
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
just getting something clear, the command doesn't get executed until u press it right?
.....
lol
@hexed anchor I couldnt get you.
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```
Go on
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?
Why do u want to use await?
uhh.. that is the only way i can turn off the bot... 🤷♂️
Theres a much easier replacement fot await
U just wanna tell the program to wait a bit right?
Before closing?
no no, i want it to close instantly when i click the shutdown button
wait wdym
Awaits task is to wait vefore executing tge given command
hmmm.. and that is the only i can logout from the discord bot so... ig i have no choice but to use it 🤷♂️
Hmm
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```
Ah
so u got whats wrong?
but it was still throwing the error... 🤷♂️
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
🤦♂️
kk, i will wait...
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
but when i use it as a simple command, it works perfectly fine... it must be some incompatibility with the tkinter..
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
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
hmm
why dont u try using a simple def?
i still dont get why ur trying to implement coroutines in your bot
just to make life easier? lol
lol no. just for the sake of realising whats the prob
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```
u just say exit()
not exit(0)
it doesnt take any args
or u can use quit() too
without passing any args
done?
@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
ok
Did you program work?
oh i have class rn so imma test it later...
Yeah sure
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
Can i implement react native with python tho ?
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
Yea i could try that
So i would need to build an api in python and make call to it with react native right ?
well yes, tho react native itself doesn't have a server receiver, you have to use node modules or sum' for that
Thanks for ur help. Going to try to implement that 😃

@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
I have already use qt but in c++, is it pretty much the same ?
yeah
almost all functions have same names
its pyqt5 in python
but tkinter is easier than any other framework in this world
ngl tho, tkinter isn't as good for a nice GUI
yea, the issue i have with those framework is that it's really hard to make something that looks really good
it is easy
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
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
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
have you looked at the qt.io page?
thats good looking for example
the 2 above are very... developer-y
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
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
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
yup
@past locust i tried the sys.exit but didnt get good results. the bot just quits down after i run it.. 🤷♂️
u need to add sys.exit() in the shutdown command
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
the code of the whole project?
yes
uh, that's much code, though I can provide a bit context if needed
yeah thatll be enough
self.text is Text object
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
if your example string is 748 and the regex is [0-9]+ thats correct tho
cause 748 are all in the range 0 to 9
ye
it adds a tag and changes the background color of the characters yellow-ish
can you show?
a screenshot with the above
regex [0-9]+
test (whatever you want, tho it should be numbers and alpha chars)
is regex a global variable?
its in a function which is in another function
def fun():
def fun():
regex = False
def fun():
...```
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
yes
the state is never kept
I dont understand
you're calling the toggle function
and set the button text
but the variable regex isn't kept
Yoda i sent u my sample code
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
well, for debugging purposes, just print regex, or stop your debugger in the toggle function
print it when
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
local variable 'regex' referenced before assignment
yes
when you assign regex, you're creating an entirely new variable
you're not reassigning/updating your desired variable
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
but if regex isn't on the global scope, (which it doesn't seem to be) it wont work correctly either
wym
it works now
thank you
I also globalled the variable in the other nested function
find
and ty 8bit as well
the new scope makes python think that's a new variable
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?)
if regex:
NameError: name 'regex' is not defined```
yes I did
I will try setting it as self attribute
yup, works again, thx
Are there any pros and cons for using MySQL with PYQT5 instead of the built in p5 sql connector?
is there a tool you guys would suggest using to making a python ui
or would you just suggest PySimpleGUI
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 *
oh ok thanks alot dude
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
hey guys will you suggest me the best way (resource) to learn Tkinter
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
@silver monolith here : https://m.youtube.com/watch?v=YXPyB4XeYLA
Learn Tkinter in this full course for beginners. Tkinter is the fastest and easiest way to create the Graphic User Interfaces (GUI applications) with Python. Tkinter comes with Python already, so there's nothing to install!
Lol ohk
just on the calculator part
U can learn from the tkinter docs too
Tkinter docs have everything
hmm
tkinter isn't a program.
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?
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
You probably want to save a reference to the parent
self.parent = parent
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
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.
Could you share more of your code? It's unclear what you're trying to do there
@digital rose it's command
@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
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
Hey does anyone know how to have text of a ui update without user input?
@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 wayeretains the reference to the Entry widget
@static cove Thanks!
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
How easy tkinter 1 to 10 guys
easy enough to get u into python guis.
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
i suggest using another thing for big big projects but tkinter is fine..good luck!
Yeah ik what u mean but we can't just disrespect tkinter like that because he our boi right.
tkinter is very good..if ur aiming for very modern uis then tkinter isnt the best
Tkinter is the stepping stone of kivy
i havent tried kivy
i tried qt and tkinter
they are both good and positive experience
I need to try qt
qt is great
I know oop
That is lovely
lol i love text editors
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
Oh nice work
node js was modern but buggy...java didnt offered a lot and python was kinda perfect in some terms
Yeah python work fine for anything because it's the way it build
python would be perfect if it wasnt slow
Definitely
c and c++ kinda harsh
But we can't expect to be perfect
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
C++ is tough I think I need alot of practice in python and JavaScript to order to even start the basic of c++
the only disadvantage soo far in c langs is being complex or too low but idk if thats a disadvantage
The logic
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
But as our brains grow through this adventures life in python and Java and JavaScript we will be able to understand c++ logic
moving from python to c++ can be a little bit strugglish
Definitely
Even I struggled learning JavaScript syntax and stopped learning it and came back to python
It's because I wasn't ready then
Now I'm ready to face anything
Because I worked with complex codes
And I make complex codes
how much experience
Almost 2 years
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
Lol
yet then just got attracted to art and did art for 4 years
i could've learnt in these 4 years
I hate art
learnt code
I failed art
digital art btw.
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
Now just doing python challenges for logical thinking and problems solving
Challenges definitely will improve thinking skills
good luck boi. i missed years and i gotta recover them since im still young
U too
does anyone here have experience with tkinter
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
^
@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
hey anyone know how to fix this issue
I am not ableto use the icon file on my tkinter app as an icon
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?
@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
b
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
@digital rose couldn't you just use a hyperlink attribute in html for each name
@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
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
perhaps
how can I debug a rather huge pyqt application ? is there any specific tool or suggestions?
perhaps
@bronze basin do you think I should move back to windows
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
I mean this project is an sort of college assingment and all of them have windows
ah that is an issue
even if u do it will be very slow to the point
where
you will just not want to
yeah
i guess you can switch back to windows? especially if its an assignment or smth
yes
interesting
np
@mint ivy breakpoints in pycharm?
what os are you on?
have you tried the others?
@eager beacon which others, using PhotoImage?
ummguys i want to ethical hack can u help me?
I have tried and failed
like send tutorial vids?
I am planning move back to windows
ummguys i want to ethical hack can u help me?
@near kraken go to #cybersecurity
k tks
this is not the right channel
sry
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?
PyQt
@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
So learning PyQt it is lol. Thanks a bunch to both of you!
finally did it
yeah anytime @dense oasis
hi
@eager beacon I should have used this from the very beginning !!!!!👍🏼👍🏼👍🏼
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
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
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
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?
how can i make my application compatible with different resolutions?
can i send the question here?
hey, can somebody help me make UI in tkinter that looks like this:
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 you should first make a qhboxlayout first and then add the layout corresponding to each part
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?
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?
title_lbl.pack(pady=20)
@vague gale
does the Curses module render the GUI on STDOUT?
where else would it go? it is the output.
like other modules makes a separate window?
@brisk sparrow head over to #game-development
@fluid tinsel almost all gui modules make a separate window. For example, Tkinter, PyQT5 etc
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!
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
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.
thanks @inner nest
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?
You can use Canvas @sand pine
?
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
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.
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?
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)
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?
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
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
@vague gale is that a tablewidget or tableview?
tablewidget
setHorizontalHeaderLabels(["col1name","col2name"])
thanks
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
firstly you design the interface and then you start adding functionality to it
What are you using for making the software?
pyQt5
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?
yeah to some extent
haven't got the grip of the window Classes and the inheritance matters of it yet tho
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
What IDE is that?
using pycharm now
And I've timed every IDE/Editor and Sublime opens the fastest out of everything if thats what you're going for
Your Sublime Free Trial Has Expired
Lol
Sublime has a trial !!
in tkinter, is it possible to time.sleep() without the program showing that it's not responding?
you would be interrupting the event loop so I don't think so
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"
look at the functionroot.after
it works! thanks!
in tkinter, is it possible to create a variable root and assing it Tk() but without opening the window?
You can do something like root.withdraw() to have it not appear when you initialize it
I believe so, yes
https://shields.io @honest bluff
We serve fast and scalable informational images as badges
for GitHub, Travis CI, Jenkins, WordPress and many more services. Use them to
track the state of your projects, or for promotional purposes.
Does anyone have any pointers on how I can go about making a web interface for a discord bot?
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.
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
@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
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 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?
I believe its not possible to have empty rows/columns. You can use padding to make spaces between items.
@ionic forge
okay! thanks
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?
@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
i thought it would be here since it's html code but ill check it out
can anyone help me with my tkinter problem, it is in #help-cherries
Python's IDLE LMAO
@vague gale DARK THEME! i had it once lol
@delicate latch use the move method 😂
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```
@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
@uncut pawn ok, then try to use toplevel window like I said before
k
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.
@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
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
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
Ahhhhh, I get it now. Alright, thank you very much for your time and help 🙂
@delicate latch Use form layout
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.
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
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?
@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
ok
guys how to install discord?
is it discord.py or discord
( i mean pip install)
pip install discord.py
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'
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.
can sm1 help me with app development and stuff
where exactly to start learning kivy from
