#user-interfaces
1 messages ยท Page 49 of 1
it'll just walk you through all of the code as it goes and you can kind of see what happens when and you'll realize where it fucked up
@latent compass just learnt that pyqt5 is pretty good
and simple to use
compared to tkinter
tkinter is a nightmare
and i learned it the hard way
@glass skiff Yes, thank you! Really!
No problem :)
closeEvent in PyQt5 is not working for some reason ```py
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
[...]
def closeEvent(self, event):
print('Closing Window!')
self.exit()
def run():
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
@keen laurel Does the function get called and just not exit, or is it an issue of the function not even being called?
I think you'd need to be inheriting from a window to be able to use it directly like that
I'm using tkinter for my gui, I'm trying to do a simple ping to an IP and have the command line parsed back into a listbox but I can't seem to make it display in the listbox at all. Looked into using os, subprocess. My current way of displaying other information in list is using .insert ---- I seem to be going down an unnecessary rabbit hole over complicating it all and was hoping someone can point me in the right direction before I waste more time
@static cove the program now uses a "QThread" rather than python threading, and I still am receiving the same error..
does anyone know why pyinstaller may all of the suden not work
Is there a way to dynamically update a layout in PySimpleGUI? I want to add things to the layout when a button is clicked, but I can't figure out how to do that (nvm, found a github issue that answers my question by overlaying it and closing the old window)
So what alignment do you want on the y axis?
what i really want most desperately is
a frame in which its size is the length of the window
and inside that frame
are buttons that are aligned as such: if there are 2 x=0.4, x=0.6 if there are 3: x=0.4,x=0.5,x=0.6
a
yes
bruh
You'll want frames for each group
Are you trying to set the size for main window to the size of the Frame?
You'll want frames for each group
@thorny spruce wdym group?
Wait, what do you mean by "if there are 2"?
Can't really get that with place I don't think
Is this not what you want?
import tkinter as tk
root = tk.Tk()
root.geometry("500x500")
frame = tk.Frame(root)
frame.pack(expand=True)
button = tk.Button(frame, text="Button!")
button.pack(side=tk.LEFT)
button2 = tk.Button(frame, text="Button2!")
button2.pack(side=tk.LEFT)
button3 = tk.Button(frame, text="Button3!")
button3.pack(side=tk.LEFT)
root.mainloop()
hey hey hey!!!
this is exactly what i want!
thanks!!
i didnt think it would be as simple as using tk.LEFT
huh
how would i change the background color of the frame @thorny spruce ?
bg="blue" doesn't seem to be working
You'll need to fill
The frame is only as large as its cotents
So you can't see anything since the buttons take up all the visible space
You could also add some padding to the frame
@keen laurel Does the function get called and just not exit, or is it an issue of the function not even being called?
@static cove Im late but function notneven being called
@mild mural If you want padding to have a border around it you may need another frame because of the button layout.
bg_frame = tk.Frame(root, bg='blue')
bg_frame.pack(expand=True, ipadx=10, ipady=10)
frame = tk.Frame(bg_frame)
frame.pack(expand=True)
internal padding
oh
there we go
now we're really cooking
also, why are the button's height and width so wonky
like
how are they proportional?
Width is adjusted to the text length
ahh ok
that makes sense
but is also very strange
can i change this line: py bg_frame.pack(expand=True, ipadx=20, ipady=30) to something that will put it in a rely position?
@thorny spruce
Not with pack, your layouts are quite box like
What layout are you trying to achieve?
ig i just want to be able to control where that whole thing is
but i want the buttons in the frame in the frame to be near the bottom
but not, aligned with the bottom
@thorny spruce
is it possible to use place() in this situation?
ayyy i got it
@thorny spruce
i made yet another frame that uses place()
here is the final code:
import tkinter as tk
root = tk.Tk()
root.geometry("500x500")
epic_frame = tk.Frame(root, bg='green')
epic_frame.place(relx=0.5, rely=0.6, anchor=tk.CENTER)
bg_frame = tk.Frame(epic_frame, bg='blue')
bg_frame.pack(expand=True, ipadx=20, ipady=30)
frame = tk.Frame(bg_frame, bg="blue")
frame.pack(expand=True)
button = tk.Button(frame, text="Button!", height=3)
button.pack(side=tk.LEFT)
button2 = tk.Button(frame, text="Button2!", height=3)
button2.pack(side=tk.LEFT)
button3 = tk.Button(frame, text="Button3!", height=3)
button3.pack(side=tk.LEFT)
root.mainloop()```
tysm for helping me out
really appreciate it
(also sry for double ping)
You can orient the frame by setting the side to the bottom and adding padding
But if it's working how you want it then that's good
๐
My QT MainWindow looks fine in QT Designer but is cut off when run. Does anybody have any suggestions?
Are you changing the window dimensions in your code?
Hi ! I there a way to "detect" an area and fill it with a specific color ?
If the user give a point is there a way to get the area around it ?
(wrong channel I think)
Currently using kivy and I was wondering if their was a simple way to find the position of a specific spot on the ui instead of having to guess and then check over and over?
I am currently creating a ui with Kivy. If I keep the window at its pre-defined size, everything is where it is supposed to be, but if I got full screen or resize the window, all of the widgets will stick to the bottom left when I need it to stay fixed at the center of the window. Any ideas how I could do this? Thanks
register.kv
<CustButton@Button>:
font_size: 32
color: .05, .05, .05, 1
size: 354, 102
background_normal: 'Controls-Button-Large-Bright-Normal.png'
background_down: 'Controls-Button-Large-Bright-Normal.png'
background_color: .88, .88, .88, 1
<TitleImage@Button>:
font_size: 32
color: .05, .05, .05, 1
size: 680, 104
background_normal: 'Welcome to Lucid..png'
background_down: 'Welcome to Lucid..png'
background_color: .88, .88, .88, 1
<RegisterWidget>:
CustButton:
text: ""
pos: 220, 100
TitleImage:
text: ""
pos: 220, 275
Hi all. I have a basic question about Tkinter. As this interface is a bit 'ugly to look at' some people like to change the font style of the interface as well as fix the design to make it look more beautiful. Does anyone know what to do or where I can look for information? Greetings to all.-
Hi @civic vale
What exactly are you asking?
The style of the text or the arrangement of the widgets in the window?
Please elaborate
and ping me please when replying
What exactly are you asking?
@modern marsh a ambas, pero mas que nada orientada al estilo de letra y a todo que este relacionado con la estรฉtica
both, but more than anything oriented to the style of letter and everything that is related to aesthetics
yes, i can help you
look at this
i will give a sample code
bAddtodb = tk.Button(mainwin, text='Add to database', height=1, width=15, font=('Bahnschrift SemiBold SemiConden', '15'), command=addtodb)
the font attribute helps in the style of text and size
for the widget placement,
place(x='',y='')
grid(row='',column='')```
can be used
for the geometry of the main window (size ,etc), this can be used,
m.geometry('500x200+100+100')```
where the first 2 are the size of the window
and the next two are the placement of the window on your screen
@civic vale
is this what you asked for?
@modern marsh
the grid if I occupy it but the first line of code that you sent me I am seeing in what it consists, if you could expand a little more it would be good. if it is not much trouble
what do you mean by expand?
ok so,
bAddtodb is a variable that i have given a value of a button
in the attributes of the button
mainwin suggests that the button must be in the window named mainwin
text is the name of the button
font consists of 2 parts
The first being any font type that you like . Ex: Arial,Canberra,etc
The second part is the size of the text put in the button
and lastly,the command part is to give a purpose to the button, the command it should execute when it is pressed
sorry for the time
ye no problem
mi first lenguaje dont is english
I am using the google translator
I am clear how to change the font style for the buttons
el tipo de letra tiene el mismo nombre que en word?
@modern marsh the font has the same name as in word?
I can do the same with entrys and labels
i did not understand what you mean by that
you write it as font in the button
font=('Arial','15')
for example
and yes
and for the background of the frame. It has a design like in powert point. Would one have to design it, for example by placing images or from somewhere can you download or use a template?
you can do the same with labels
i am not sure about entries
I am not very familiar with frames, sorry
font=('Arial','15')
@modern marsh i understand
btw
ahh ok
it is better to switch to PyQt5
instead of tkinter
as tkinter is very old and difficult to use
ahh ok
What is the difference between tkinter and PyQt5
My goal is to make this look as cute as possible
In pyqt5 there is a designer app
that helps you to put all the widgets manually
instead of coding it
omg
but then that becomes lines of code. Why would they review the program's code lines?
i did not understand
what do you mean it becomes lines of code?
this is the UI for designing the window
what do you mean it becomes lines of code?
@modern marsh Es que me piden que la interfaz sea programada.
entonces la persona que lo revisara le va a echar un vistaso a las lรญneas de codigo
then the person who will review it will take a look at the code lines
PyQt5 is in the same language as python?
gracias por la ayuda voy a investigar un poco por mi cuenta ahora.
thanks for the help i'm going to do some research on my own now.
Could I ask you questions from time to time regarding tkinter?
ok
@civic vale Well in my opinion, TKinter is good simple and great for many things as aside from big projects, yet PyQt5 has more potentiality at its rate of power, simply to put it TKinter is Simple and Easy, and PyQt5 is Powerful.
@modern marsh TKinter might be old, yet there is a way to avoid its plain look of things, You can change the UI looks. To be more modern by using ttkThemes.
Like for Example:
Yeah!
Just takes about 3 Lines of Code to Extract teh Themes.
Also, if you are interested in the different themes you may as well look here: https://ttkthemes.readthedocs.io/en/latest/themes.html
thanks!
Hi i'm a bit confused between using tkinter and pyqt5, can anyone suggest? [ I know tkinter but it seems to be pretty basic]
I am a python begginer and am making a tkinter calculator - I am trying to make a popup for when you click the radical button so you can enter the index (square root, cube root, etc). But when ever I click the button in the pop-up that is linked to this function - it will input the index into the main calculator but it won't close the index window. *Note: the enter function puts whatever I pass through it into the main calculator, and the root_evaluation is the inputted index. And the root_gui is the second window defined as a
Toplevel()
Code for the function that I want to input the index and close the window:
try:
global root_gui
global root_expression
root_evaluation = eval(str(root_expression))
enter(root_evaluation)
root_gui.destroy
except:
root_display.set(" Error ")
root_expression = ""```
I have also tried all 3 of
```root_gui.destroy()```
```root_gui.quit```
```root_gui.quit()```
in place of
```root_gui.destroy```
So should I do wxPython or Pyqt5
Is it easy?
but how would it know which toplevel to destroy
it has an easy ui interface
oh ok
I just tried Toplevel.destroy()
root_gui.destroy() must work as per i have tried before
yes send whole code
I tried root_gui.destroy()
!paste
put it in hastebin
whats that
go here
paste code
click save
then copy url and paste here
@midnight bramble
ye the bot is ded for now lol
Hey
do you know how to use ttk themes
in tkinter?
imma be back in an hour
yes
@modern marsh LOL, I thought you meant "pastebin" instead of "hastebin", never heard of hastebin.
oh well never heard of it.
Me too heard of pastebin.
ye
hastebin is very similar to pastebin, just overall better and much much lighter
its like comparing Atom to pycharm
I assume I'd ask this here but: How would I go about renaming a program? For instance: I Want to change where it says "BBC Iplayer" Here to "Bruh-player"
anyone familiar with selenium here?? if yes pls ping me
I'm a python beginner and am creating a tkinter calculator. I'm trying to add a function for radicals with variable indexes (so u can do square root, cube root, 4rth root, etc.). I thought I had it all working but I'm getting an error message that says line 34, in equal_enter evaluation = str(eval(expression)) File "<string>", line 1, in <module> TypeError: 'Button' object is not callable. Can someone help - I will send the code after this (not all the code - just the buttons that you need for a radical input and calculation)
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ok
https://paste.pythondiscord.com/rejumotimu.py (this is the code - i deleted the multiple messages where i pasted parts of the code)
anyone here?
People are here, but you haven't asked anything
oh
ok
so im confused on rkinter
from tkinter import *
root = Tk()
myLabel = Label(root,text='hello')
myLabel.pack()
root.mainloop()
I did this but i dont fully nderstand
Which lines don't you understand?
1-4
root = Tk() This is defining your Tk instance, which is needed to have of the tkinter code to work. It specifically creates a toplevel widget of Tk and each instance has its own Tcl interpreter. This is what will contain and show most your GUI
what is Tk
myLabel = Label(root, text="hello") This is creating a tkinter widget called Label. You're telling it it should be associated with your root Tk instance, so it'll be tied to that associated Tcl interpreter. Then you tell it what text to display
ok i understand that
Tk is the name for the graphical user interface that tkinter is a binding of
Mhm, you need an instance of the Tcl interpreter and the Tk toolkit that interfaces it if you want you tkinter code to run
Tk() does all that for you
So you're created your label, but you haven't told the program how/where to place it in the window. There are 3 different ways to do that: .pack(), .place(), and .grid().
That code uses .pack() to put the widget into the window.
whats the difference between pack and lace and grid
Finally root.mainloop(). That's you saying you've gotten all the GUI code ready to go and you're reading to actually show the window and let the user interact with it. .mainloop() shows the window and listens for user input. Any code you have after this line won't run until the user closes all open GUI windows, because it's a blocking function.
ok
Here's an okay-ish article for the different between the 3 different geometry managers: pack, place, and grid.
https://subscription.packtpub.com/book/application_development/9781785889738/1/ch01lvl1sec14/the-tkinter-geometry-manager
Anyone know any good applications to make the prototype of the user interface?
Anyone know any good applications to make the prototype of the user interface?
@silent walrus
Bootstrap Studio is decent
Unless you mean like wireframes, then maybe adobe xd
hey so i have a field that requires a URL but i want to be able to use PIL and i don't know how to do that. any ideas?
Is there an opensource alternative for bootstrap studio?
@silent walrus i use balsamiq
can someone suggest a nice webdesign for 6 divs that have unequal text .i tried stacking them 3 in 1 row and 3 in next but it looks bad
please can anyone help me if so please ping with a answer
please
I would guess this is where all the Tkinter stuff goes.
def saveText():
theText = textBox.get("1.0",END)
print(str(theText))
file = filedialog.asksaveasfile(mode="w", defaultextension=".txt")
if file is None:
return
save_file = str(theText.get(1.0, "end-1c"))
print(save_file)
file.write(save_file)
file.close()
Is there any reason this wouldn't write "theText" to the file?
if not can anyone explain to me why or how this would/would
work.
@.me if you would like to help
is there a way to make kivy constantly update the text that it is displaying
Can I DISABLE a button in tkinter with args?
is there a way to make kivy constantly update the text that it is displaying
@digital rose Yes, a loop.
I tried a while loop my window crashed @bright trout
@digital rose oh lol
@digital rose Hm.. A loop should work but, tried for loop?
Doesnt Kivy have a mainloop like TKinter?
Weird. I am testing out pysimplegui on a MacBook. It installs just fine but when I try to run a hello world app, it says no module found
could someone explain what is happening here, when the window gets smaller you should be able to scroll around the pannel but its has this weird thing like its trying to draw/paint over itslef
can I ask question related to Kivy library here? as it is an UI library
yes
@dark basalt how can I make a widget the same size as the window?
i don't know the answer, i'm just saying you can ask here
when ever I make a widget, they are just 100,100. I want it so that it covers the window
from a quick google you need to use a Layout
use a Layout widget, put your widget inside of it
in PyQt5 i have window1 -> opens window2 -> opens window3. if window3 has a problem i want to close window3 and 2 and return to window1. how do i return or throw/catch something between QmainWindows?
ok guys just a quick question i have this self.calendar.setMaximumDate(QDate(currentYear, currentMonth + 1, calendar.monthrange(currentYear, currentMonth)[1])) i'm using PyQt5 and i'm wondering what is the use of the [1]
the resolution of the image is more than the window what i do ?
from tkinter import *
from PIL import Image, ImageTk
class GUI:
def __init__(self, root):
self.root = root
self.root.title('Test')
self.root.geometry('1350x700+0+0')
self.bg = ImageTk.PhotoImage(file='./images/pexels-juan-733475.jpg')
self.root.state('zoomed')
bg = (Label(self.root, image=self.bg).place(x=0, y=0))
if __name__ == "__main__":
root = Tk()
__object__ = GUI(root)
root.mainloop()```
how do i fix this
https://www.pexels.com/photo/photography-of-night-sky-733475/ this is the real image (with info)
You need to rescale the image to the size of your window. So you can do something like
image = Image.open('./pexels-juan-733475.jpg').resize((1350,700), Image.ANTIALIAS)
self.bg = ImageTk.PhotoImage(image)
Is pysimplegui worth learning? Is it that much easier than something like appJar or PyQt?
@autumn badge Depends on the application. You can learn the basics of any GUI framework in a day.
Of course. I went away from QT for licensing reasons
I am just curious how easy it is to have buttons and different commands In pysimplegui
I mainly do things like calculators or document builders for apps so mostly single window apps where I need a snappy front end to tie into the meat of the back end
@autumn badge For that use, it's not a bad choice.
I have built exe's with it using pyinstaller
You can get a GUI up and running fast.
nice. i have been using appjar and when i exe the files, there is a 10-20 second lag
@neon bay have you seen FBS on github? it is a pyqt builder similar to how electron is set up
@autumn badge There's some lag when running with PyInstaller, nothing too bad. Usually have a "splash screen" users are looking for.
I have not, I will take a look though
lemme find the link
Is there anything unexpected about pyautogui on Windows vs Mac?
I was able to get someone's code that uses pyautogui to work on my computer (windows) without making any changes to what they wrote
but it doesn't work on their computer (Mac)
@neon bay https://github.com/mherrmann/fbs-tutorial
@wise path i have had issues with lots of guis with my mac
anyone know how to set a InputText() in pysimpleGUI to int only?
something like an InputInt
Using PySide2, how would I call a function when a combobox's selection is changed
combo.activated[str].connect(self.onChanged)
def onChanged(self, text):
self.qlabel.setText(text)```
something like that @spark turtle
Thanks.
!e
print("FTW")
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Say I have a Flask based website, mostly ready front-end wise with its templates, js, css, Ajax, rest api, and so on. I'm thinking of making an Android app for it, but I'm a complete novice for Android development.
What's in your opinion the fastest or best approach?
when trying to install Kivy i am getting ERROR: Failed building wheel for Cython
/// Failed to build Cython
what to do ?
@main bloom How are you installing kivy? the exact command you're typing?
well i think i got the issue it says
error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/
at the very down
and
and i am not sure which one to download
@static cove
I don't see that error in the error message you posted. Also, humor me with how you're installing kivy. You're probably running python 3.8 considering the error message and kivy has special install instructions for 3.8
at the very bottom you can see the error ... hmmm
i didn't know there is another way for python 3.8
what i did was
1 sec
i installed the dependency you can see in blue .. but when i am trying to install Kivy itself at the very top
i am unable to
that's what i did
Check the first pin in this channel. That's what you need to type in the PyCharm terminal to install kivy properly
pip install --pre --extra-index-url=https://kivy.org/downloads/simple kivy[base]
?
ok
hmm i did that but
it installed a lot of things but when i type Import kivy i am still getting an error
should i uninstall the dependency i did before ? cause it doesn't donload and override them
I would uninstall it just in case, then re-try that pip command
sure
but otherwise, let me boot up PyCharm and check what happens with mine
i uninstalled all dependency and did same command again .. and i got this
Are you running in a venv in PyCharm or using the user python?
there is some kivy related stuff i think it got installed when i was trying the commands showing in kivy websites
hmmm
venv ? i am sorry what is that ?
i am using pycharm .. if that's what you're asking about
PyCharm, by default, likes to create virtual environments for python. Which will generally keep packages in their own environment separate from the global/system python and separate from other virtual environments. It's very useful.
In PyCharm, can you go to Settings -> Project: <your project name> -> Project Interpreter and tell me what it says in that window?
So your pycharm is running a virtual environment (as indicated by the little green v)
okaaaay
So to install packages in a virtual environment, you need to use the virtual environment python interpreter. The PyCharm terminal should default to that, so you want to use that instead of the regular system cmd line/terminal.
so typing pip install --pre --extra-index-url=https://kivy.org/downloads/simple kivy[base] in specifically the PyCharm terminal should install the package to that venv
ok doing that now
cause i did it only on CMD
dude
you're
a legend
Thanks so much man
i just didn't know there is a difference between using these commands on CMD or in pycharm terminal
@main bloom yeah! Virtual environments are super useful. Here's a good article explaining it that you can read when you have some time: https://realpython.com/python-virtual-environments-a-primer/
can teens in India apply for a tkinter thing?
wdym a tkinter thing
as a tkinter programmer
idk
most companies use libraries such as PyQT5 for apps mostly because it's easier
but it comes with licensing fees
can we use PyQt for mobile development?
yes i guess
it's better to use whatever language that mobile device is written in
but it's possible
does it require OOP?
Can I ask Pyqt questions here?
hi
i've posted a question about PyQt5 in the #help-carrot channel if anybody could take a look! โค๏ธ
how to use python for electron.js
Any feedbacks on this design? I feel like this is not the best design for a music player haha
- The exit button is redundant
- Instead of a restart button, add previous and next buttons. The previous button will work as a restart button, unless the song is already at the beginning, in which case it'll go back 1 track.
- Light/dark mode and about should be more hidden, like in a context menu revealed by a small button in a corner or a hamburger menu?
- PreAmp boost doesn't seem like an often-adjusted setting. You could make the UI switch between showing the boost and the volume, but not sure what the most intuitive way to do that would be. Maybe clicking on the "volume" label
- Pause and stop should use the traditional โธ๏ธ and โน๏ธ icons rather than the giant buttons
- Add a seek bar along with the elapsed time and total song length
- Display some more metadata about the song: album, year, genre, album art
- I don't know what the browse music window looks like, but the features described above could and should be integrated into the browse music window since they're gonna make what you have way more compact. @plush stream
@sudden coral thank you so much, and yeah i'm fully agree with you, i'm planning to add menu bar and fill it with the about button, and dark mode button, as for the seek bar I don't think it's possible to do it with tkinter? (please correct me if i'm wrong) and im also planning on supporting playlist.
Not sure about the seek bar; I don't use tkinter. Could you implement it like you did the volume slider, but automatically update its position every second as the song plays?
I've had that idea too, but unfortunately vlc's Python binding doesn't seems to have that feature, either i have to migrate to C or just use other audio engine, but i have a hard time finding them. So if you have recommendations, please share.
what can we do with tkinter?
@plush stream I've made a music player using Pyside2 (Qt) before.
It was really simple since the Qt Multimedia module comes with a bunch of widgets and APIs for it.
File "<ipython-input-14-a3c061cc4457>", line 2
import chart-studio.plotly.graph_objs
^
SyntaxError: invalid syntax
why am i getting a syntax error when i import chart-studio?
yep it was a underscore
but
ModuleNotFoundError: No module named 'chart_studio'
now i got this
even after pip installing "chart_studio"
it's to the same interpreter
you know what? i think i'm gonna work on animating my map with the mapbox stuff on jsfiddle
What ide did you use?
jupyter
Hmm, not so sure abt that then, sorry.
it's fine ty tho
If you used pycharm reinstalling the module from pycharm itself will fix the problem, you can install the module via project settings > interpreter > add module (in form of + button). Maybe it's similar with Jupyter? I never use it
you have an environment problem
did you try !pip install chart_studio in the Jupyter notebook itself?
i did
yes, i was thinking i have some issue w my env so i directly installed it on jupyter
ig i'll try to make my data visualization w jsfiddle + mapbox satellite api
so i can check if my ML model is making sense
hey guys is there any recommendations for ui builders (in python) that I can use. It's for my business to display data from an api
yes
@digital rose i don't think its popular but I use wxpython with that you can download wxformbuilder and get pretty far into the GUI building process, if its a very simple app then it can probably get you pretty far
that being said this is the only way i am familliar with so there may be better options
:/
btn_no(state=DISABLED) TypeError: 'Button' object is not callable
(TKinter), I am trying to DISABLE Button 'No', after Button 'Yes' is clicked..
where can i learn pyqt5?
is there a way in pyqt5 to check upon connecting the condition say i want to connect to a host i want to be able to check if
If host is not reachable = offline
if connected = online
Hi! I am new to python and decided to make a simple calculator.. I am away from home atm so I can't show the code until tomorrow... But I can send pics that I took on my phone.. I have only created the GUI but I can't seem to put the buttons together.. Any help?
I mean idk how to eliminate those gray spaces in between the red buttons ๐ค
I tried moving the buttons along the rows and column but that doesn't solve it...
I have a speculation that it is bc of the "Clear" button but if that is the case then its even more complicated ๐
There should be an option to tell clear to use 3 cells rather than use 1 and be 3 cells wide. rowspan
When making canvas what is the difference between using root. Height and self. Height imean both do the same thing I don't get it
Iam talking about kivy btw
Depends how stacked the rule is. They arent always the same
Is there is anyway in pycharm to know the attributes required cause sometimes I forget the name of the attributes needed
Such as these attributes
@tribal path iam sorry but what is this? Like I download it and in pycharm iwill se an indicator of what attributes ican use in this location?
Havent used it myself, but yea should exactly that. Like what you get for .py files
There may be other more recent versions from elsewhere, just noticed how old it is
https://github.com/noembryo/KV4Jetbrains heres one
@tribal path thanks man that was very useful didn't know there is such thing
!close
There should be an option to tell clear to use 3 cells rather than use 1 and be 3 cells wide.
rowspan
@tribal path OK thx I will try that.
ok so I started the project yesterday and will continue in a few hours. Is it good?
the one on the bottom is the newest one
@digital rose good job man keep it up ๐
thx
ok so
basicly
I need help in beetween> I tried moving the buttons along the rows and column but that doesn't solve it...
@digital rose ok so basically I need help here:
clear = Button(gui, text='Clear', fg='black', bg='darkred',
command=lambda: press(), height=2, width=21)
clear.grid(row=6, column=1)
I need to eliminate those gray spaces and press everything together
and rowspan / columnspan doesn't do anything
I need an answer fast if possible pls๐
if I put
clear.grid(row=6, column=1, columnspan=3)
this is happening
a more detailed pic
I need helpppp
i am not familiar much with tkinter but it looks like you messed a bit with columnspan. Just a specualtion....
@novel cloud ikr
k so I'm bak but I can't code today I can just take notes on my phone and implement the code another time
back*
brb
Oh fair enough i dont know tinker but i can understand the code n possibly help with it
ok im back
@novel cloud are you gonna help me or
pls
can anybody help me????
it now looks like this
clear = Button(gui, text='Clear', fg='black', bg='darkred',
command=lambda: press(), height=2, width=24)
clear.grid(row=6, column=0, columnspan=3)
any help pls????
pls I need helppp๐ญ
How would I go about creating a file browser sort of thing? Basically just display a grid of thumbnails and then be able to do have one of them "selected"
is anybody gonna help me or
the whole code or just for the Clear button?
I can't share the whole code cuz it's too long but I'll share the clear button
clear = Button(gui, text='Clear', fg='black', bg='darkred',
command=lambda: press(), height=2, width=24)
clear.grid(row=6, column=0, columnspan=3)
@novel cloud
then just increase the width n u sud be fine
what the width of ur whole grid
horizontally
??
Driver code
if name == "main":
# create a GUI window
gui = Tk()
# set the background colour of GUI window
gui.configure(background="gray")
# set the title of GUI window
gui.title("Calculator")
# set the configuration of GUI window
gui.geometry("330x240")
# make the GUI window irresizable
gui.resizable(False, False)
240
I think
button1 = Button(gui, text='1', fg='black', bg='darkred',
command=lambda: press(1), height=2, width=6)
button1.grid(row=2, column=0)
idk
like the gap?
yea
u havent set it up?
i havent used tinkerbefore so we r on same page bahaha
this is gonna be difficult 
I assigned the size for the first button and then copy pasted the size for every button except the clear button
u dont do it like that its really inefficent but lets try to work it out with what u have here ๐
i will try my best upto my capability
since u dont have any other options atm
button1.grid(row=2, column=0) -----> is that for placing the button in the grid??
ye
brb 5min
k im back
can you help me with the grid?
but like
should we talk in sms?
dms*
its sud be fine here
k
its pretty dead here
ik
ok thx cuz I pretty much have no idea ๐
yea
let me see the doc
clear = Button(gui, text='Clear', fg='black', bg='darkred',
command=lambda: press(), height=2, width=24, padx = 0) #------> add padx to 0 n sud be fine :D
clear.grid(row=6, column=0, columnspan=3)```
i wanted to see what happens after that
yea the thing is...
coz u need to probably make the width to 26
defending on what the defaul padding was
k the thing is I can stay at the pc for like 10 mins
hope so
depends on how qucik u are
k im gonna run the code now but I gotta wait for the Compiler to load
cuz i just started the program
u r using python ?
how u runnign compiler
having u tried increasing the width
the width is 24
what happens if u try that
set it to how much
make it 26
k
n show me the diff
nothing changed either
i thought the reason was something else
ok I think I'm gonna put 27
k I put 28
sweet beans
make the grid width to be 96
for the whole gui?
yes bud
bbhahaha
try to test 200 lol
๐
u gotta keep trying
also
yes sir ?
y when I run the compiler
ye interpreter
it first opens up a window called tk that I have to close it to open the actual calculator
hhahaha its probabyl something with ur coding m8
๐๐๐๐๐
did that happen after u kept it to 200?
nah it happened for when I ran the program for the first time
and 8dk what the problem is
k
I wanna like get rid of the gaps and then make the buttons squircle
but that's another story for another time
so can we like get rid of the gaps somehow?
@novel cloud
padx and pady to 0
on the clear button?
all the buttons
smh
ok ur whole codebase is a mess
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
k
and post ur code there n send me link here
give me few mins im teaching my niece abcd
k
bruh wtf
u press function does take any argument
but y r u passing the value in ur press function
๐
did u get it from u rm8 ?
?
it's ok
in ur line 15
brb
def press(value = ""): #-----> add an argument for the function like this that defaullt as empty string```
this is for removing the error and does make ur calculator work
i recommend doing that
but ye its ur choice
i recommend u try to make the whole thing from start on ur own
yea that's gonna be a total mess
just to understand underlying mechanics to make it work
so like do I just delete everything?
if u want to learn how to code
brb
and just doing it for ur assignment n def a better option
k im bak but I think I'm gonna brb again
k so I'm gonna delete the whole code and than try to code something
or like watch a tutorial idk
bye?
k bye๐๐ค
lol sure bud best of luck
Can I ask questions about Pyqt?
PyQt5 question;
the QtWebSockets has a signal socket.error is there any signal for checking if i connected successfully to aswell? this is what i have so far
PyQt5 question;
Error: QThread: Destroyed while thread is still running
self.download_anime_Thread = dict()
self.download_anime_Thread[anime] = Download_Video(data=data) self.download_anime_Thread[anime].download_video.connect(self.download_anime_task) self.download_anime_Thread[anime].start()
Guys can i ask something about pyside
Asking good questions will yield a much higher chance of a quick response:
โข Don't ask to ask your question, just go ahead and tell us your problem.
โข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โข Try to solve the problem on your own first, we're not going to write code for you.
โข Show us the code you've tried and any errors or unexpected results it's giving.
โข Be patient while we're helping you.
You can find a much more detailed explanation on our website.
guys
I am trying to change the tk default icon to a png that I downloaded. How can I change the icon?
and also when I run the command it first shows this and I have to close it to open the calculator
and the "Calculator" name doesn't fit in the window..
pls I need help asap!!
plssss helpppp๐
erh.... pyqt5 does it not have a signal like "socket.error"? :S i want to be able to give a message when connected to a host!
@wraith belfry QWebSocket should have a connected signal
@static cove i have been trying that but does not work like the "socket.error" signal :S apparently
let me try it one more time
It's emitted when a socket is connected and the handshake was successful. Are you looking for something else?
aaah i remember why i couldn't get it to work!
it's because i need it to be a custom signal!
@static cove it worked this time ๐ wtf
i have no clue as to what i did wrong the last time :S
well at least it's working??
yupp ๐
@static cove question, can i put custom variables with my custom signal? :S
Yeah, you can pass data through a custom signal. You just need to make sure you specify what datatype you're passing across
@maiden dragon Hey, I know you had some issues with wxPython, anything that still needs resolving?
@static cove always have issues but all the ones i posted about are good now lol, i do have to learn python to SQL since we need to read the data from sql and not have it just stored in memory so we shall see how "fun" that is
pretty sure all my problems now are me not knowing matplotlib well enough and having poor API documentiation for the program i write to.
learning custom drawing was a nightmare and a half. Actually that still is partially broken so i could post that at some point ๐
anyone here ever use PyQT having some issues with positioning of Graphics in a Graphical Scene, but out of curiosity first what does PyQT coordinate system look like? does it start in the top left?
I think 0,0 is centered on the QGraphicsView. From the little that I've played with it, I remember having to set the scene size for it to behave in a consistent manner, otherwise it'll auto-adjust (and therefore the origin will change) based on what you add.
@maiden dragon I think Sqlite3 is a good database to start off with since it's bundled with sql, a flat file, and relatively easy to work with
That is the behavior I am noticing too, I know there is a local coordinate system for the graphic and then the global/scene coordinate system but I am unsure how to tell the graphic to move position (say to the bottom of the Graphic view)
So I think you need to set the Scene size with setSceneRect and then you should be able to move items to the correct position with setPos? I believe the origin of the item is also the center of the item.
@static cove i believe i need to get ms sql server management studio from what my coworker told me, then i just have to read and write to it through the python sql module of my choice, which i can lookingto Sqlite3 for that
Is there any way to view errors that come when a curses window is open? I dont believe I can wrap it in curses.wrapper because Im calling the code within a class, but feel free to tell me otherwise. Its just hard to code when you have no clue what is happening
Hey if anyone is able to help me let me know im really new to python and this is my first time using tkinter (picked up subject this year) wanted to know if anyone could help me as I cant seem to find a way to add more rows and columns to this
from Tkinter import Frame, Label, Message, StringVar
from Tkconstants import *
except ImportError:
from tkinter import Frame, Label, Message, StringVar
from tkinter.constants import *
class Cell(Frame):
"""Base class for cells"""
class Data_Cell(Cell):
def __init__(self, master, variable, anchor=W, bordercolor=None, borderwidth=1, padx=0, pady=0, background=None,
foreground=None, font=None):
Cell.__init__(self, master, background=background, highlightbackground=bordercolor, highlightcolor=bordercolor,
highlightthickness=borderwidth, bd=0)
self._message_widget = Message(self, textvariable=variable, font=font, background=background,
foreground=foreground)
self._message_widget.pack(expand=True, padx=padx, pady=pady, anchor=anchor)
self.bind("<Configure>", self._on_configure)
def _on_configure(self, event):
self._message_widget.configure(width=event.width)```
def __init__(self, master, text, bordercolor=None, borderwidth=1, padx=None, pady=None, background=None,
foreground=None, font=None, anchor=CENTER):
Cell.__init__(self, master, background=background, highlightbackground=bordercolor, highlightcolor=bordercolor,
highlightthickness=borderwidth, bd=0)
self._header_label = Label(self, text=text, background=background, foreground=foreground, font=font)
self._header_label.pack(padx=padx, pady=pady, expand=True)
if bordercolor is not None:
separator = Frame(self, height=2, background=bordercolor, bd=0, highlightthickness=0, class_="Separator")
separator.pack(fill=X, anchor=anchor)
class Table(Frame):
def __init__(self, master, columns, column_weights=None, column_minwidths=None, height=None, minwidth=20,
minheight=20, padx=5, pady=5, cell_font=None, cell_foreground="black", cell_background="white",
cell_anchor=W, header_font=None, header_background="white", header_foreground="black",
header_anchor=CENTER, bordercolor="#999999", innerborder=True, outerborder=True,
stripped_rows=("#EEEEEE", "white"), on_change_data=None):
outerborder_width = 1 if outerborder else 0
Frame.__init__(self, master, highlightbackground=bordercolor, highlightcolor=bordercolor,
highlightthickness=outerborder_width, bd=0)```
self._cell_background = cell_background
self._cell_foreground = cell_foreground
self._cell_font = cell_font
self._cell_anchor = cell_anchor
self._number_of_rows = 0
self._number_of_columns = len(columns)
self._stripped_rows = stripped_rows
self._padx = padx
self._pady = pady
self._bordercolor = bordercolor
self._innerborder_width = 1 if innerborder else 0
self._data_vars = []
self._columns = columns
for j in range(len(columns)):
column_name = columns[j]
header_cell = Header_Cell(self, text=column_name, borderwidth=self._innerborder_width, font=header_font,
background=header_background, foreground=header_foreground, padx=padx, pady=pady,
bordercolor=bordercolor, anchor=header_anchor)
header_cell.grid(row=0, column=j, sticky=N + E + W + S)
if column_weights is None:
for j in range(len(columns)):
self.grid_columnconfigure(j, weight=1)
else:
for j, weight in enumerate(column_weights):
self.grid_columnconfigure(j, weight=weight)
if column_minwidths is not None:
self.update_idletasks()
for j, minwidth in enumerate(column_minwidths):
if minwidth is None:
header_cell = self.grid_slaves(row=0, column=j)[0]
minwidth = header_cell.winfo_reqwidth()
self.grid_columnconfigure(j, minsize=minwidth)```
if height is not None:
self._append_n_rows(height)
self._on_change_data = on_change_data
def _append_n_rows(self, n):
number_of_rows = self._number_of_rows
number_of_columns = self._number_of_columns
for i in range(number_of_rows + 1, number_of_rows + n + 1):
list_of_vars = []
for j in range(number_of_columns):
var = StringVar()
list_of_vars.append(var)
if self._stripped_rows:
cell = Data_Cell(self, borderwidth=self._innerborder_width, variable=var,
bordercolor=self._bordercolor, padx=self._padx, pady=self._pady,
background=self._stripped_rows[(i + 1) % 2], foreground=self._cell_foreground,
font=self._cell_font, anchor=self._cell_anchor)
else:
cell = Data_Cell(self, borderwidth=self._innerborder_width, variable=var,
bordercolor=self._bordercolor, padx=self._padx, pady=self._pady,
background=self._cell_background, foreground=self._cell_foreground,
font=self._cell_font, anchor=self._cell_anchor)
cell.grid(row=i, column=j, sticky=N + E + W + S)
self._data_vars.append(list_of_vars)
self._number_of_rows += n
def _pop_n_rows(self, n):
number_of_rows = self._number_of_rows
number_of_columns = self._number_of_columns
for i in range(number_of_rows - n + 1, number_of_rows + 1):
for j in range(number_of_columns):
self.grid_slaves(row=i, column=j)[0].destroy()```
self._number_of_rows -= n
def set_data(self, data):
n = len(data)
m = len(data[0])
number_of_rows = self._number_of_rows
if number_of_rows > n:
self._pop_n_rows(number_of_rows - n)
elif number_of_rows < n:
self._append_n_rows(n - number_of_rows)
for i in range(n):
for j in range(m):
self._data_vars[i][j].set(data[i][j])
if self._on_change_data is not None: self._on_change_data()
def get_data(self):
number_of_rows = self._number_of_rows
number_of_columns = self._number_of_columns
data = []
for i in range(number_of_rows):
row = []
row_of_vars = self._data_vars[i]
for j in range(number_of_columns):
cell_data = row_of_vars[j].get()
row.append(cell_data)
data.append(row)
return data
@property
def number_of_rows(self):
return self._number_of_rows
@property
def number_of_columns(self):
return self._number_of_columns```
number_of_columns = self._number_of_columns
if data is None:
row = []
row_of_vars = self._data_vars[index]
for j in range(number_of_columns):
row.append(row_of_vars[j].get())
return row
else:
if len(data) != number_of_columns:
raise ValueError("data has no %d elements: %s" % (number_of_columns, data))
row_of_vars = self._data_vars[index]
for j in range(number_of_columns):
row_of_vars[index][j].set(data[j])
if self._on_change_data is not None: self._on_change_data()
def column(self, index, data=None):
number_of_rows = self._number_of_rows
if data is None:
column = []```
Hey @tame blaze!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
column.append(self._data_vars[i][index].get())
return column
else:
if len(data) != number_of_rows:
raise ValueError("data has no %d elements: %s" % (number_of_rows, data))
for i in range(self._number_of_columns):
self._data_vars[i][index].set(data[i])
if self._on_change_data is not None: self._on_change_data()
def clear(self):
number_of_rows = self._number_of_rows
number_of_columns = self._number_of_columns
for i in range(number_of_rows):
for j in range(number_of_columns):
self._data_vars[i][j].set("")
if self._on_change_data is not None: self._on_change_data()
def delete_row(self, index):
i = index
while i < self._number_of_rows:
row_of_vars_1 = self._data_vars[i]
row_of_vars_2 = self._data_vars[i + 1]```
j = 0
while j < self._number_of_columns:
row_of_vars_1[j].set(row_of_vars_2[j])
i += 1
self._pop_n_rows(1)
if self._on_change_data is not None: self._on_change_data()
def insert_row(self, data, index=END):
self._append_n_rows(1)
if index == END:
index = self._number_of_rows - 1
i = self._number_of_rows - 1
while i > index:
row_of_vars_1 = self._data_vars[i - 1]
row_of_vars_2 = self._data_vars[i]
j = 0
while j < self._number_of_columns:
row_of_vars_2[j].set(row_of_vars_1[j])
j += 1
i -= 1
list_of_cell_vars = self._data_vars[index]
for cell_var, cell_data in zip(list_of_cell_vars, data):
cell_var.set(cell_data)
if self._on_change_data is not None: self._on_change_data()```
def cell(self, row, column, data=None):
"""Get the value of a table cell"""
if data is None:
return self._data_vars[row][column].get()
else:
self._data_vars[row][column].set(data)
if self._on_change_data is not None: self._on_change_data()
def __getitem__(self, index):
if isinstance(index, tuple):
row, column = index
return self.cell(row, column)
else:
raise Exception("Row and column indices are required")
def __setitem__(self, index, value):
if isinstance(index, tuple):
row, column = index
self.cell(row, column, value)
else:
raise Exception("Row and column indices are required")
def on_change_data(self, callback):
self._on_change_data = callback```
if __name__ == "__main__":
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk
root = Tk()
table = Table(root, ["column A", "column B", "column C"], column_minwidths=[None, None, None])
table.pack(expand=True, fill=X, padx=10, pady=10)
table.set_data([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
table.cell(0, 0, " a fdas fasd fasdf asdf asdfasdf asdf asdfa sdfas asd sadf ")
root.mainloop()```
jesus that was alot
!pastebin
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
m trying to run slenium python on linux
it works but send_keys is not wortking
on shell
I have some doubt in plotly dash and need help
which format would you guys recomend for creating a help document, It would be nice to have a table of contents as well as a search functionality
i think this can be done easily through some HTML (though i have no experience with HTML) right now i was atempting to use a rich text editor
looks like HTML is deffinatly the way to go so this should be fun
@maiden dragon what are you documenting and who is your audience
how to use a GUI application I built and the audience is the chemical engineering undergraduate students who will be using it
Are they cloning your code and running it from there? Plain text/Markdown and CTRL+F work pretty well if you've got a small(-ish) amount of information.
its getting compiled to a .exe and being run from VM's
Maybe PyInstaller Spec Files? https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-data-files
@storm spire if that was aimed at me i already use py installer spec files i was just telling them thats how it is being implimented now :p
can someone test my project?(especially if you're on a mac)
https://github.com/shyam1998/movie-recommendation-system-GUI
any place where i could get some help regarding kivymd.....reddit, discord server, anywhere.....
Pyqt5 Question:
how does one add additional data / custom variable to a signal?
self.socket.connReady.connect(lambda : self.ready_on(board))
def ready_on(self, board):
self.ui.FRAME_MAIN.raise_()
this crashes my program :S
in my GUI i have a Connecting to host text message but i want to have like a ... animation after the text like
Connecting to host.
Connecting to host..
Connecting to host...
Connecting to host.
Connecting to host..
Connecting to host...
how?
from tkinter import *
root = Tk()
root.geometry("400x400")
class App:
def __init__(self, master):
myframe = Frame(master)
myframe.place(relwidth=1,relheight=1)
self.btn = Button(master, text = "click", command = self.clicker(master))
self.btn.place(x=100,y=100)
def clicker(self, master):
frame = Frame(master)
frame.place(relwidth=1,relheight=1)
self.labz = Label(master, text = "working")
self.labz.place(x=100,y=200)
App(root)
root.mainloop()```
i want the "working" msg to show when i click the button, but it is showing right after i run the program..
what changes shud i make?
i have question: is there possibility to use my own custom graphics as program gui's ? i cannot find any info about that
Hey all, how would I bind this button event to the parent frame please? ```py
event_hierarchy.py
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
super().__init__(parent)
button = wx.Button(self, label='Press Me')
self.Bind(wx.EVT_BUTTON, self.panel_button_handler, button) # bind to MyPanel, multiple widgets, same event
button.Bind(wx.EVT_BUTTON, self.on_button_press) # bind to button
def panel_button_handler(self, event):
print('panel_button_event_handler_called')
def on_button_press(self, event):
print('on_button_press called')
event.Skip() # event goes up to the next handler, in this case, panel_button_handler()
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='Hello World')
panel = MyPanel(self)
self.Show()
events bubble up, remove event.Skip() call to stop events bubbling up
button = bottom layer
MyPanel = next layer up
MyFrame = top layer
if name == 'main':
app = wx.App(redirect=False)
frame = MyFrame()
app.MainLoop()
how do I bind the frame to the wx.EVT_BUTTON?
# event_hierarchy.py
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
super().__init__(parent)
button = wx.Button(self, label='Press Me')
parent.Bind(wx.EVT_BUTTON, self.frame_button_handler, button) # bind to MyFrame, multiple widgets, same event
self.Bind(wx.EVT_BUTTON, self.panel_button_handler, button) # bind to MyPanel, multiple widgets, same event
button.Bind(wx.EVT_BUTTON, self.on_button_press) # bind to button
def frame_button_handler(self, event):
print('frame_button_event_handler_called')
def panel_button_handler(self, event):
print('panel_button_event_handler_called')
event.Skip()
def on_button_press(self, event):
print('on_button_press called')
event.Skip() # event goes up to the next handler, in this case, panel_button_handler()
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='Hello World')
panel = MyPanel(self)
self.Show()
# events bubble up, remove event.Skip() call to stop events bubbling up
# button = bottom layer
# MyPanel = next layer up
# MyFrame = top layer
if __name__ == '__main__':
app = wx.App(redirect=False)
frame = MyFrame()
app.MainLoop()
worked it out, call the parent (just posting in case anyone else is interested)
from tkinter import *
root = Tk()
root.geometry("400x400")
class App:
def __init__(self, master):
myframe = Frame(master)
myframe.place(relwidth=1,relheight=1)
self.btn = Button(master, text = "click", command = self.clicker(master))
self.btn.place(x=100,y=100)
def clicker(self, master):
frame = Frame(master)
frame.place(relwidth=1,relheight=1)
self.labz = Label(master, text = "working")
self.labz.place(x=100,y=200)
App(root)
root.mainloop()```
@hot wasp command = lambda _e: self.clicker(master)
So I am working on a sorting algorithm and am trying to update my QT scene every iteration or maybe every x iteration but how would I go about doing this?
I am just using a bubble sort here is the code
def bubbleSort(self):
n = len(self.values)
for i in range(n - 1):
for j in range(0, n - i - 1):
if self.values[j].scenePos().y() > self.values[j + 1].scenePos().y():
# Update Graphic Positions
self.switch(self.values[j], self.values[j + 1])
# Update Position in List
self.values[j], self.values[j + 1] = self.values[j + 1], self.values[j]
how would I be able to update my graphics view every iteration?
guys how can i convert my kivy project i made into APK to use it on android ?
hey I'm new but does anyone know how i can use a gui (pyqt5) with another piece of python code?
Does anybody know the consequences of using normal multithreading compared to pyqts QThreading?
@wraith belfry So typically you would create a custom signal and when you're establishing the custom signal, you would indicate what kind of data you're passing through it
@violet rivet Pyqt/pyside2's thread functions + classes are thread safe. So you don't need to worry about implementing queues and keeping tracking of threads. You just pick your implementation and go. Plus there are usually signals with the Qts threads that are useful
I have not had any luck with them so if I am able to use normal multithreading library I will try that out
@static cove
https://stackoverflow.com/questions/63432716/update-qt-elements-over-course-of-for-loop-pyqt5
@mighty rock if i type lambda _e: ...it says syntax error...but when i just type lambda: self.clicker(master)...it works!
thanks @mighty rock !!๐
๐
PyQt5 Question:
When this runs it ONLY prints out the boards that are ONLINE! not the once that are offline :S why?
self.ping = QTimer(self)
self.ping.start(1000)
self.ping.timeout.connect(self.pingServer)
def pingServer(self):
for key, value in self.board.items():
self.socketPing = Socket(host=(value["ip"]))
self.pingBoard = value["Name"]
self.socketPing.pingError.connect(self.pingError)
self.socketPing.connReady.connect(self.pingReady)
self.socketPing.Connect()
def pingError(self):
self.board[self.pingBoard]['Status'] = "Offline"
print(self.pingBoard + " is Offline")
def pingReady(self):
self.board[self.pingBoard]['Status'] = "Online"
print(self.pingBoard + " is Online")
just a question, PyQT vs Kivy? and reason?
Depends on what kind of application you need, I'd say qt is more suited for normal desktop apps, while kivy offers more direct customization for something that's completely custom and it's written for python instead of having to be a wrapper like PyQt/PySide
QT: How do I make a text entry which only creates a new line if the user is holding both shift and enter, otherwise activates a signal?
Do I have to make a whole new widget or is there a simpler way?
class Entry(QtWidgets.QTextEdit):
returnPressed = QtCore.pyqtSignal()
def keyPressEvent(self, e: QtGui.QKeyEvent) -> None:
if e.key() == QtCore.Qt.Key_Enter or e.key() == QtCore.Qt.Key_Return and \
not e.modifiers() & QtCore.Qt.ShiftModifier:
self.returnPressed.emit()
return
return super(Entry, self).keyPressEvent(e)
it seems to work so nvm I guess
I hope I do not block anything important
Sorry quick question, if I have an object that is stored in an array and I call that object and I wanted it to return an int. What dunder could I use to call that value when I call the class. I dont want to do
int(values[0]) -> 1
but rather values[0] -> 1
I guess that wouldn't necessarily work, so never mind
it was a pretty stupid question, Basically I was looking for a way to have QtRects in a list to return the height value of those objects by calling something like list[0] where that would return the height of the object instead of doing something like int(list[0])
something like that wouldnt work becuase you would grab a reference to the height of the object and you would no longer have an actual reference to the object itself
@violet rivet So I haven
Welp. Let me try that again without hitting enter too soon
I haven't forgotten about the problem that you posted, just hitting a curious case where even if correctly threaded something about the QGraphicsView and QGraphicsScene isn't behaving. I think it has something to do with the event loop misbehaving, but I'm diving into it a bit more to figure it out
Guys can u suggest a yt channel which uses kivy lang instead of just python ?
@tame blaze what do you mean export a root to an excel file?
Is there any way to change a label using Tkinter after the window has been opened?
Or rather, the mainloop has been ran
Is the label change triggered by anything? Like the user pressing a button
Then in the function that the button triggers when it's pressed, you could add code to change the label
can anybody who has experience with tkinter help me on something?
basically i wanna create a grid minesweeper style
height and width based on user input
Actually the thing that I'm trying to do is, within a function triggered by another Tkinter window, I'm trying to open a Tkinter loop, and do the things from there.
while also closing the main Tkinter window that's caused all this.
@karmic vessel When you say "open a tkinter loop" what do you mean?
So you want one tkinter window to open another one and do the work in that other window?
So, for the second window I would look into the toplevel() function, to spawn a new high level window that can then run it's own function and things. You generally only want one .mainloop() for a tcl instance. But I'd need to see how you lay out your program to give more specific advice.
Hey @karmic vessel!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Ah
My Qt app just quits without any errors
tried abbreviating the code as much as i could.
https://paste.pythondiscord.com/qikevasiqi.cs
unless you count "QThread: Destroyed while thread is still running"
wait
if your main window is hidden
and you close a secondary window
should the app close?
not necessarily
turns out the code, even without shortening it, was broken in itself.
app.setQuitOnLastWindowClosed(False) solved it
@hollow pewter ... so you're good or nah?
yeah
hm, turns out I didn't need to use "toplevel" apparently.
oh, it's Toplevel() iirc
Oddly enough, if I put "tkinter.Toplevel(nowPlaying)" in there, I get 2 windows.
Please could I get some help im unsure of why I got this error
from PIL import ImageTk,Image
import sqlite3
root = Tk()
root = Tk(className='LIBRARY SYSTEM')
root.geometry("1200x800")
#database
#Create a database or connect to one
conn = sqlite3.connect('book_system.db')
#create cursor
cur = conn.cursor()
#create table
'''
cur.execute("""CREATE TABLE Books (
book_name text,
book_ISBN integer,
student_name text,
date_borrowed integer,
outstanding_yn integer
)""")
'''
#create submit function for database
def submit():
#clear the text boxes
b_name.delete(0, END)
b_isbn.delete(0, END)
s_name.delete(0, END)
d_borrowed.delete(0, END)
outstanding_yn.delete(0, END)
#Create a database or connect to one
conn = sqlite3.connect('book_system.db')
#create cursor
cur = conn.cursor()
#insert into table
cur.execute("INSERT INTO library VALUES (:b_name, :b_isbn, :s_name, :d_borrowed, :outstanding_yn)",
{
'b_name': b_name.get(),
'b_isbn': b_isbn.get(),
's_name': s_name.get(),
'd_borrowed': d_borrowed.get(),
'outstanding_yn': outstanding_yn(),
})
#commit changes
conn.commit()
#Close connection
conn.close()
#creates table boxes
b_name = Entry(root, width=30)
b_name.grid(row=0, column=1, padx=20)
b_isbn = Entry(root, width=30)
b_isbn.grid(row=1, column=1)
s_name = Entry(root, width=30)
s_name.grid(row=2, column=1)
d_borrowed = Entry(root, width=30)
d_borrowed.grid(row=3, column=1)
outstanding_yn = Entry(root, width=30)
outstanding_yn.grid(row=4, column=1)
#create table box labels
b_name_label = Label(root, text="Book Title")
b_name_label.grid(row=0, column=0)
b_isbn_label = Label(root, text="Book ISBN")
b_isbn_label.grid(row=1, column=0)
s_name_label = Label(root, text="Student Name")
s_name_label.grid(row=2, column=0)
d_borrowed_label = Label(root, text="Date Borrowed")
d_borrowed_label.grid(row=3, column=0)
outstanding_yn_label = Label(root, text="Outstanding")
outstanding_yn_label.grid(row=4, column=0)
#create submit button
submit_btn = Button(root, text="Add Entry To Database", command=submit)
submit_btn.grid(row=6, column=0, columnspan=2, pady=10, padx=10, ipadx=100)
#commit changes
conn.commit()
#Close connection
conn.close()
root.mainloop()```
what are you trying to do when you say outstanding_yn()? do you mean outstanding_yn.get() like the other functions there?
you're fine, we're here to help!
Hello fellas, just got into python programming a few days ago, and got to a question i'm rather confused:
I need to do a script to compare 2 values, A and B:
while A is bigger than B, the script will endlessly ask for new A and B inputs.
if A and B are equal, it will display a message saying they're equals, and willl continue to ask for new A and B inputs.
lastly, if B is higher than A, the script will display a message saying such, and end the script.
I can't get out of the loops, even when writing contraditory inputs. Can anyone help this noob?
๐
@timid mica read about conditional statements
QtWidgets.QApplication.restoreOverrideCursor() does not work
any ideas why?
unsetCursor works nvm
how do I get a list of all the installed fonts using Tkinter? I'm using
fontlist = tkinter.font.families()
and it doesn't work.
guys im new to kivy and learning it with the help of yt vids so i tried doing this code
# Python file
import kivy
from kivy.app import App
from kivy.config import Config
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '150')
kv = Builder.load_file("krxls.kv")
class LoginPage(Screen):
pass
class RegisterPage(Screen):
pass
class WindowManager(ScreenManager):
pass
class KrxLS(App):
def build(self):
return kv
if __name__ == "__main__":
KrxLS().run()
WindowManager:
LoginPage:
RegisterPage:
<LoginPage>:
name: "lp"
GridLayout:
cols: 1
Label:
text: "Login!!"
GridLayout:
cols: 2
Label:
text: "Username"
TextInput:
multiline: "False"
Label:
text: "Password"
TextInput:
multiline: "False"
Button:
text: "Sign up"
on_release: app.root.current = "rp"
Button:
text: "Sign in!"
<RegisterPage>:
name: "rp"
GridLayout:
cols: 1
Label:
text: "Register!!"
GridLayout:
cols: 2
Label:
text: "Username"
TextInput:
multiline: "False"
Label:
text: "Password"
TextInput:
multiline: "False"
Button:
text: "Sign in"
on_release: app.root.current = "lp"
Button:
text: "Sign Up!"```
but im getting this error
Traceback (most recent call last):
File "/Users/Kushi/PycharmProjects/Beginner/GUIDev/kivyGUI.py", line 12, in <module>
kv = Builder.load_file("krxls.kv")
File "/Users/Kushi/PycharmProjects/Beginner/venv/lib/python3.7/site-packages/kivy/lang/builder.py", line 301, in load_file
return self.load_string(data, **kwargs)
File "/Users/Kushi/PycharmProjects/Beginner/venv/lib/python3.7/site-packages/kivy/lang/builder.py", line 399, in load_string
widget = Factory.get(parser.root.name)(__no_builder=True)
File "/Users/Kushi/PycharmProjects/Beginner/venv/lib/python3.7/site-packages/kivy/factory.py", line 131, in __getattr__
raise FactoryException('Unknown class <%s>' % name)
kivy.factory.FactoryException: Unknown class <WindowManager>```
Please help
import tkinter as t
m=t.Tk()
C=t.Canvas(bg="gray",height=500,width=500)
C.create_arc(0,0,500,500,start=18,extent=72,fill="orange")
C.create_arc(0,0,500,500,start=288,extent=90,fill="dark blue")
C.create_arc(0,0,500,500,start=180,extent=108,fill="red")
C.create_arc(0,0,500,500,start=162,extent=18,fill="blue")
C.create_arc(0,0,500,500,start=90,extent=72,fill="light blue")
C.create_text(text="Hi")
C.pack()
m.mainloop()
``````py
Traceback (most recent call last):
File "C:/Users/Church/PycharmProjects/weird/g_a_m_e.py", line 9, in <module>
C.create_text(text="Hi")
File "C:\Users\Church\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2805, in create_text
return self._create('text', args, kw)
File "C:\Users\Church\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2766, in _create
cnf = args[-1]
IndexError: tuple index out of range
@static cove
I'm very new to tkinater
Trying to make a pie chart
So you want to provide the position of the text as one of the first arguments
Here's the parameters it takes: http://www.effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_text-method
so: C.create_text(x, y, text="Hi")
Ooohh
xD
so:
C.create_text(x, y, text="Hi")
@static cove well um- no error, but no text either
Did you put in exactly what I had, or did you fill in the x, y values with where you'd like to place it?
Ha, yeah. That can happen with positioning close to edges
for create_text you'd need to set a specific font and pass in the size as part of setting the font
font=("name_of_font", size)
Hello I'm trying to learn tkinter and how to properly structure it and I have issues
import tkinter
class Application(tkinter.Frame):
def __init__(self, parent):
tkinter.Frame.__init__(self, parent)
self.parent = parent
self.create()
self.pack()
def create(self):
self.entry1 = tkinter.Entry(self, width=30)
self.entry2 = tkinter.Entry(self, width=10)
self.scale = tkinter.Scale(self, orient=tkinter.HORIZONTAL, showvalue=0, length=185)
self.button = tkinter.Button(self, width=14)
self.entry1.place(relx=0.5, rely=0.35, anchor=tkinter.CENTER)
self.entry2.place(relx=0.3, rely=0.65, anchor=tkinter.CENTER)
self.scale.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER)
self.button.place(relx=0.63, rely=0.65, anchor=tkinter.CENTER)
def main():
root = tkinter.Tk()
root.geometry("300x200")
root.resizable(width=False, height=False)
root.title("please end me")
Application(root)
root.mainloop()
if __name__ == "__main__":
main()
Does anyone know why nothing is showing up
- is this the best way to structure my code?
just wondering, can QTimer break when calling it from another file? having some issues with a function that worked fine in the same file as the application but is breaking when the function is in a different file
@digital rose In your create() function, you want to place those items in self.parent, not self to get them to show up in the root window.
Oh ok thanks
trying to install kivy but i am getting this error
am i installing kivy in wrong way ?
pip3 install kivy==2.0.0rc3 if thats python3.8
@tribal path thanks man you're a legend
pip3 install kivy==2.0.0rc3if thats python3.8
@tribal path but how do i do it with pipenv
Shouldnt be any/much different afaik. so pipenv install kivy==2.0.0rc3
what is the best way to do ui in python?
What are the best options available for building cross platform apps? I am new to UI development and I have a Python Flask server using which I'm serving a Single Page Application(used HTML, Bootstrap and JS for this). I currently run this app on Ubuntu in a browser.
If I have to run this app on other platforms like Android, are there other ways besides redoing it in native android code?
Kivy potentially, or at least p4a. Utilising a webview of some sort to display your html. The Qt5 can be comiled to apps as well afaik
hello i need help with how to make a bot accessable to edit by 2 people
does anyone know how to set the onscreen start location for a gui using pyside2
hello how do i make it so it deletes the previous output? for example it types hello, and i want it so when i click the button again it deletes the hello and then outputs something again
if i make it to do a random.choice of a list i have
the choices just pile below
i want it to delete the previous one
Hello, I'm writing a program with GUI, I'm trying to use tkinter, but in mac it gives me some visual errors. Do you know if there's a better package to do that? I'm quite newbie with all this stuff...
@digital rose try pyqt
@digital rose oh, thank you
how would I change the background of a slave frame in tkinter
RamColorButton = tk.Button(DLocations,text='Ram Button',command=lambda: (DimmOne.RamDimm.LED0.bg = 'blue') )
# I am trying to set a frame color but said frame is declaired in a different file and returned to this one
# but it does appear in the GUI so I assume it is still loaded into memory and editable
# So I want to do something like "DimmOne.RamDimm.LED0.bg = 'blue'"
something like that
I am trying to make an effects engine for OpenRGB and I need a way to visualize it in the software
im trying to make a dice roll app and i was wondering how do i show photo when i click a button
what is the purpose of the bin() function?
!d bin
bin(x)```
Convert an integer number to a binary string prefixed with โ0bโ. The result is a valid Python expression. If *x* is not a Python [`int`](#int "int") object, it has to define an [`__index__()`](../reference/datamodel.html#object.__index__ "object.__index__") method that returns an integer. Some examples:
```py
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
``` If prefix โ0bโ is desired or not, you can use either of the following ways.
```py
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
``` See also [`format()`](#format "format") for more information.
!d format
format(value[, format_spec])```
Convert a *value* to a โformattedโ representation, as controlled by *format\_spec*. The interpretation of *format\_spec* will depend on the type of the *value* argument, however there is a standard formatting syntax that is used by most built-in types: [Format Specification Mini-Language](string.html#formatspec).
The default *format\_spec* is an empty string which usually gives the same effect as calling [`str(value)`](stdtypes.html#str "str").
A call to `format(value, format_spec)` is translated to `type(value).__format__(value, format_spec)` which bypasses the instance dictionary when searching for the valueโs [`__format__()`](../reference/datamodel.html#object.__format__ "object.__format__") method. A [`TypeError`](exceptions.html#TypeError "TypeError") exception is raised if the method search reaches [`object`](#object "object") and the *format\_spec* is non-empty, or if either the *format\_spec* or the return value are not strings.... [read more](https://docs.python.org/3/library/functions.html#format)
How do I make a paint app with python?
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
โข These are backticks, not quotes. Backticks can usually be found on the tilde key.
โข You can also use py as the language instead of python
โข The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
!code
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
โข These are backticks, not quotes. Backticks can usually be found on the tilde key.
โข You can also use py as the language instead of python
โข The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
I want to make a GUI similar to this. What framework is best for this? I know basics of python
I would try some kind of web framework or kivy.
guys why people say Python is not good for GUI apps ? while there is some good packages such as Kivy >?
Python is just fine for GUI apps but not the best if you need to โcompileโ them for normal users
@digital rose kivy or remi would be a good choice
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
It seems to be running now but I end up getting an error related to PIL any advice?
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/LibrarySystem/venv/Library GUI main.py", line 3, in <module>
from PIL import Image
ModuleNotFoundError: No module named 'PIL'
Process finished with exit code 1
My guess it is either not installed or corrupted
Did you recently update python @tame blaze
yeah but I reinstalled pillow
is this channel related to tkinter
How do you program like this man?
Just when i type bot commands on wrong channel it automatically redirects to #bot-commands ๐
why when i change the colour of the vertical scroll bar in textedit in qt designer it shows properly on like the designing screen but on the preview it reverts back to the default scroll bar?
which lib will u recommend for me
tkinter is super easy for start
@here
@onyx barn You want to use a StringVar and then set the text equal to that StringVar
And what exactly is a stringvar
may i request some help with my tkinter import, the PIL isnt importing for pictures
is there something wrong with th eimport
I want to create a login menu for my PyGame game, I have done this with a Notes system in tkinter, and was wondering, should I use the tkinter interface, or should I try to replicate it in PyGame?
Is there any way that a bunch of tkinter buttons call the same function but work deferently.
For e.g.
I have a list of names , I want to iterate through the list and create buttons with the text same as the corresponding name , and when the buttons are pressed they print their coeresponding name.
@granite escarp DM me.
oh that's cool
Hello folks, how do I make these functions start a thread only once?
def send_message(self) -> None:
"""
Generates and sends the message
"""
self.init_conn()
self.msg = MIMEMultipart()
self.msg['From'] = self.email
self.msg['To'] = self.kindle_email
self.to_covert = self.var.get()
if self.to_covert == 'no_convert':
self.msg['Subject'] = ""
elif self.to_covert == 'convert':
self.msg['Subject'] = "convert" # Indicate that the files need to be converted to .azw3 format
self.msg.attach(MIMEText("Books", 'plain'))
for path in self.files:
part = MIMEBase('application', 'octet-stream')
with open(path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
f'attachment; filename={Path(path).name}')
self.msg.attach(part)
self.email_conn.sendmail(self.email, [self.kindle_email], self.msg.as_string())
self.email_conn.quit()
def invoke_send(self) -> None:
"""
Helper function for invoking 'send_message' method
"""
self.send_button = Button(self.frame, text='Send!', bg='yellow', width=20,
font=self.courier12, command=threading.Thread(target=self.send_message).start)
self.send_button.place(x=325, y=300, height=25)
@onyx barn Here's a decent explanation of the different Variable classes tkinter provides https://effbot.org/tkinterbook/variable.htm
ty
@tame blaze I had the same issue and found that when I would pip install it, my environment was still set to the older version of python.
Hey could I please get some help with Tkinter? I can't figure out why my checkbuttons change colors when I hover over them with mouse. First image is how they look when mouse isn't over them and how I want them to look, second image is with the cursor hovering over it. Thank you kindly!
How can I add the buttons side by side? I used .pack() method
@proven oyster What kind of styling logic are you using with tkinter?
@digital rose You can specify the side with button1.pack(side=tk.LEFT) or tk.RIGHT. That should left you place it side by side.
For more complex placements though you might have to explore multiple frames with the grid manager and the pack manager
tkinter has grid? nice
@static cove I apologize I can't copy paste the actual code right now; the program is running inside a VM and using 100% of memory so I can't open a browser or discord on the VM to do so. Here's what I have though.
it's my first time using Tkinter so I'm probably just being dumb and missing something but I did go through the docs I could find and tried all the self.configure options with no success
can someone tell me why my pysimplegui window closes whenever i press a button in it?
