#user-interfaces
1 messages · Page 40 of 1
my instinct would be to just print whenever something changes (like, when worker 3 finishes print "worker 3 finished" once) instead of trying to make a live updating positional display
but i don't know if your worker library can do that
Ah, one of the polish points for this is that it can manage to show the status of each worker in order.
just printing them as they finish/fail is a step backwards
huh, personally i think "what order things happened in" is more meaningful than "the order in the list of workers" but i guess it's not my assignment
okie, I shall await any other suggestions :D
anyway, if you're printing all ten of them every time through the loop, the move_up*position ends up doing more printing than necessary
I'm not, the loop is over active_workers
and printing them with regular line breaks at the end avoids the need to flush stdout
wait, does that remove workers when they're finished or an error? then how do you print those
yep. There is a check for finished workers which are removed from the active workers list and have their status printed for the last time; just... elided that.
hmm idk then
okie, I shall await any other suggestions :D
Any nice UI design modules?
Are there any other visual strong libraries in python besides tkinter, Because tkinter is Nice I suppose But Really... visually atractive... maybe also a more flexable one?
Pyside 2 is an option
yo
someone help plsss
import tkinter as tk
import requests
from tkinter import font
root = tk.Tk()
root.title('GradeHelper')
root.geometry('1920x1080')
# root.iconbitmap('sun_icon.ico')
canvas = tk.Canvas(root, height=1920, width=1080)
canvas.pack()
def start_menu():
label['text'] = 'Welcome to GradeHelper'
label['font'] = ('Eina02-Bold', 50)
label.place(relwidth=1, relheight=1)
button['text'] = 'Start learning.'
button.place(relx=0.7, relheight=1, relwidth=0.3)
frame = tk.Frame(root, bg='#99ccff', bd=5)
frame.place(relwidth=1, relheight=1)
mainframe = tk.Frame(root, bg='white', bd=5)
mainframe.place(relwidth=0.9, relheight=0.8, relx=0.5,rely=0.1, anchor='n')
entry = tk.Entry(mainframe, font=('Eina02-Bold',20), bd=2)
#entry.place(relwidth=0.65, relheight=1)
button = tk.Button(mainframe, bd=3, font=('Eina02-Bold',16))
# button.place(relx=0.7, relheight=1, relwidth=0.3)
# lower_frame = tk.Frame(root, bg='#99ccff', bd=15)
# lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')
label = tk.Label(mainframe, font=('Eina02-Bold',20), justify='center')
start_menu()
# """
root.mainloop()
howcome my button doesnt show up
I'd like to know something : is it possible to create a single (custom) tkinter canvas item ? Say I want to extend the Canvas class with a "create_bezier" method, would it be possible to group all the lines making that bezier curve into a single object id ?
haven't found anything in the docs
I suppose I'd have to create tags for that
but I wonder if there is a better way
@craggy talon it's because although you can read from the global scope at any time, you can't write without the global keyword. But that is a terrible way to design a GUI with tkinter, as it's something that greatly benefits from OOP
whats a better way you suggest? @grim bronze
import tkinter as tk
class MainWindow(tk.Frame):
def __init__(master=None):
super().__init__(master)
self.canvas = tk.Canvas(self, height=1920, width=1080) # use self.master.winfo_height or self.master.winfo_width to adapt to different
# screen resolutions
self.button = tk.Button(self, bd=3, font=('Eina02-Bold',16), text="Start Learning")
self.label = tk.Label(self, text="Welcome to GradeHelper", font=('Eina02-Bold', 50), justify="center")
self.entry = = tk.Entry(mainframe, font=('Eina02-Bold',20), bd=2)
self.label.grid(row=0, column=0)
self.button.grid(row=0, column=1)
self.entry.grid(row=0, column=2
self.canvas.grid(row=1, column=0, columnspan=3, sticky="nswe")
if __name__ == '__main__':
root = tk.Tk()
root.title('GradeHelper')
root.geometry('1920x1080')
gui = MainWindow(root)
gui.grid(sticky="nswe")
root.mainloop()
Hello dear Kivy specialists!
I have an issue with the ScreenManager. It just doesn't swap screens, no errors or anything.
Setup:
class RadioPlayButtonScreen(Screen):
pass
class RadioStopButtonScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
.kv
ScreenManagement:
transition: FadeTransition()
RadioPlayButtonScreen:
RadioStopButtonScreen:
<ScreenManagement>:
<RadioPlayButtonScreen>:
name: 'RPBtn'
Button:
text: 'Play'
on_press: app.Radio.radio_play()
on_release: app.root.current = 'RSBtn'
<RadioStopButtonScreen>:
name: 'RSBtn'
Button:
text: 'Stop'
on_press: app.Radio.radio_stop()
on_release: app.root.current = 'RPBtn'
What am I doing wrong?
I must note that this screenmanagement is inside a floatlayout.
I need some help with a very small tkinter project
please @ or dm me if you're familiar with tkinter and I will send my code
thank you.
@loud sapphire so your app.root is not screenmanagement, right? Maybe it is FloatLayout etc.
I mean maybe you need something like screenmanagement.current : 'RPBtn'
hmm.. so I'd have to refer to ScreenManagement via id?
I get this then:
AttributeError: 'super' object has no attribute '__getattr__'
@loud sapphire
You cannot access the ID defined in the widget tree while inside a specific rule.
You can specify these relations directly in the tree:
ScreenManagement:
id: sm
transition: FadeTransition()
RadioPlayButtonScreen:
on_release: sm.current = 'RSBtn'
RadioStopButtonScreen:
on_release: sm.current = 'RPBtn'
something like this
Damn, I was hoping to keep the RadioScreen part as one separate component.
Actually I don
t think it helped
although I seem to be confused, wait a second.
you can do something like this
from kivy.app import App
from kivy.lang import Builder
KV = """
FloatLayout
MyLabel
text: '123456'
<MyLabel@Label>
on_touch_down: print(app.root)
"""
class MyApp(App):
def build(self):
self.root = Builder.load_string(KV)
MyApp().run()
So on release should work too
@loud sapphire something like this should work
from kivy.app import App
from kivy.lang import Builder
KV = """
FloatLayout
ScreenManager
id: sm
Screen1
text: 'screen1'
Screen2
text: 'screen2'
<Screen1@Screen>
text: ''
name: '1'
on_touch_down: app.root.ids['sm'].current = '2'
Label
text: root.text
<Screen2@Screen>
text: ''
name: '2'
on_touch_down: app.root.ids['sm'].current = '1'
Label
text: root.text
"""
class MyApp(App):
def build(self):
self.root = Builder.load_string(KV)
MyApp().run()
AttributeError: 'super' object has no attribute '__getattr__'
Still run into this. I remember it being something that the class is not instanciated yet?
@loud sapphire could you give more error info?
could you change MyApp to something like this
class MyApp(App):
def build(self):
self.root = Builder.load_file('My.kv')
or
class MyApp(App):
def build(self):
return Builder.load_file('My.kv')
where My.kv is your kv file
This works for me in this case
tho I'm not good at loading kv files (I just load kv strings)
@loud sapphire
Thats what I do already.
Thats a really odd error
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
class Screen1(Screen):
pass
class Screen2(Screen):
pass
class MyApp(App):
def build(self):
return Builder.load_file('My.kv')
MyApp().run()
My.kv:
FloatLayout
ScreenManager
id: sm
Screen1
text: 'screen1'
Screen2
text: 'screen2'
<Screen1>
text: ''
name: '1'
on_touch_down: app.root.ids.sm.current = '2'
Label
text: root.text
<Screen2>
text: ''
name: '2'
on_touch_down: app.root.ids.sm.current = '1'
Label
text: root.text
this is working code (although you can check it out)
just try to compare it with your one.
it would be very simple if you removed all the "excess" from your code that does not affect the presence of an error.
I always do that 🙂
Aghhh
It closes immediately without errors if I move it into a structure like yours.
I removed the clutter
FloatLayout
ScreenManager
id: sm
Screen1
text: 'screen1'
Screen2
text: 'screen2
Can't I have this part like this instead?
FloatLayout:
<FloatLayout>:
ScreenManager
id: sm
Screen1
text: 'screen1'
Screen2
text: 'screen2
And in any case, if my own set-up doesn't work, how come it doesn't error?
It just doesn't swap the screen
FloatLayout:
<FloatLayout>:
this won't work
you can do something like
MyFloatLayout
<MyFloatLayout@FloatLayout>
ScreenManager
id: sm
Screen1
text: 'screen1'
Screen2
text: 'screen2'
or
MyFloatLayout
<MyFloatLayout>
ScreenManager
id: sm
Screen1
text: 'screen1'
Screen2
text: 'screen2'
in py define new widget class:
class MyFloatLayout(FloatLayout):
....
Ah, yes, thats what I did. I called it RadioLayout. Just used the example code for the question.
you can show the code, preferably minimal (where the error occurs)
hey guys any idea how could i connect something like this :
arrayResults[1] = test1()
button_RTC = tk.Button(mainWindow, text="RTC Test", font=40,bg='#928987', command=test1)
button_RTC.place(relx=0, rely=0.65, relwidth=0.1, relheight=0.05)
how can i connect the arrayResult to a button?
Thanks for helping last week me2beats! I had to rush into the week, was too busy to get back to my project
``
import tkinter as tk
root = tk.Tk()
def open_window():
top = tk.Toplevel(root)
sleep_for is just a function I made for the timer
root.after(sleep_for, open_window)
root.withdraw()
root.after(sleep_for, root.deiconify())
root.mainloop()
``
Whenever I withdraw my root, it will keep a blank window open until after the timer ends. When I deiconify(), it replaces the blank window with the original one I had. The top will open as intended to though. How do I make it so the blank window never appears in the time between when I set my top to open. Please tell me if you need any more info to answer the question.
Is this the place to ask for help for PyQt?
I'm having trouble understanding how to use isSignalConnected() method which accepts a QMetaMethod as a parameter. I need to detect if a signal is connected to one of my QObjects before disconnecting the signal. (I can disconnect the signal fine, just need help with isSignalConnected() usage).
@twilit plinth Well in c++ you'd get it with QMetaMethod::fromSignal but that doesn't seem to exist in python
It looks like a pain in the ass in python
You can use QObject.metaObject() to get a QMetaObject
Then use QMetaObject.indexOfSignal("signalname") to get an index
then QMetaObject.method(index) to finally get a QMetaMethod
Have not tried any of this. Just did some digging with the docs
https://github.com/PyQt5/PyQt/blob/master/Demo/IsSignalConnected.py#L40 this is how you do it with pyqt apparently
oh that's doing the same thing mark said anyway
@sudden coral @proper glade thank you both. Works perfect
@sudden coral @proper glade I spook too soon. I keep getting an index of -1.
sorry trying to fix formatting
Don't think the parenthesis are meant to be part of the signal name
The meta object has a way to get all methods iirc
You should iterate them and see what the signal is supposed to be called
ok
Good luck with it. I'm going to bed so I won't be around to respond until morning
Maybe meta or someone else can meanwhile
np, thanks for the help! will give it a shot
@twilit plinth you have to be a bit more specific with the signature
so currentChanged(int) rather than just currentChanged()
Ok, it's working for the layoutChanged portion. I don't understand what the int is for though. I thought currentChanged() was emitted whenever the current tab was changed.
Oh I see
https://doc.qt.io/qt-5/qabstractitemmodel.html#layoutChanged im not sure how you're supposed to normalize this signature
but it's working right?
yes. it gave me a positive integer for the layoutChanged index and it appears to be working properly.
but always -1 for currentChanged
did you change it to currentChanged(int)
i.e. .indexOfMethod("currentChanged(int)")
ohhh
yes
i think it's going to work because my first print statement gave me 32
instead of -1
ok working fine now
thanks!
import PyQt5.Qt as qt
signature_cache = dict()
def method_signatures(q_object: qt.QObject):
try:
return signature_cache[type(q_object)]
except KeyError:
meta_object = q_object.metaObject()
methods = (
meta_object.method(i) for i in range(
meta_object.methodCount()
)
)
signatures = {
method.name().data().decode():
method.methodSignature().data().decode()
for method in methods
}
signature_cache[type(q_object)] = signatures
return signatures
here's a helper function you can use to get signatures quickly @twilit plinth
returns a dict of name: signature
>>> pprint(method_signatures(qt.QWidget()))
{'_q_reregisterTimers': '_q_reregisterTimers(void*)',
'_q_showIfNotHidden': '_q_showIfNotHidden()',
'close': 'close()',
'customContextMenuRequested': 'customContextMenuRequested(QPoint)',
'deleteLater': 'deleteLater()',
'destroyed': 'destroyed()',
'grab': 'grab()',
'hide': 'hide()',
'lower': 'lower()',
'objectNameChanged': 'objectNameChanged(QString)',
'raise': 'raise()',
'repaint': 'repaint()',
'setDisabled': 'setDisabled(bool)',
'setEnabled': 'setEnabled(bool)',
'setFocus': 'setFocus()',
'setHidden': 'setHidden(bool)',
'setStyleSheet': 'setStyleSheet(QString)',
'setVisible': 'setVisible(bool)',
'setWindowModified': 'setWindowModified(bool)',
'setWindowTitle': 'setWindowTitle(QString)',
'show': 'show()',
'showFullScreen': 'showFullScreen()',
'showMaximized': 'showMaximized()',
'showMinimized': 'showMinimized()',
'showNormal': 'showNormal()',
'update': 'update()',
'updateMicroFocus': 'updateMicroFocus()',
'windowIconChanged': 'windowIconChanged(QIcon)',
'windowIconTextChanged': 'windowIconTextChanged(QString)',
'windowTitleChanged': 'windowTitleChanged(QString)'}
>>>
@proper glade awesome thanks
How TF do i get a widget's grid info/data in tkinter? I specifically need to know the padx and pady of a widget...
You can set StringVar, IntVar etc and use the get method with the widget their in with the name of the Var to retrieve it
StringVars/IntVars for the values within .grid
I didn't know you could use StringVar/IntVars in grid, thx
Problem is what I'm trying to do is loop through all objects that don't have padx/pady set in .grid and set it to 5 and I don't think making 2 new IntVars for every single widget is a nice solution here :/
I can already loop through all my widgets, that's easy but I need to check their padx/pady which currently sounds like a nightmare
You can always set a load of IntVars in an array
There’s probably an easier way to do it though. Just using regular vars in a class for example
Not seen that one
Lemme double check...
You can always do ALT+M in the regular Python IDE, type in Tkinter and look through the grid code
Is there a built in method in Tkinter for resizing a widget using the mouse when the program is running?
I’ve tried searching but I can only find mouse down events and mouse co ordinates which would be painful with the grid manager.
@stone hatch, I read up on the grid info method and I think this should work.
info = widget.grid_info()
padx = info[“padx”]
pady = info[“pady”]
In PyQt, I'm trying to impletement a QSortFilterProxyModel in my model/view so that I can do some custom sorting. However, when I switch my view to this proxy model then it seems like emitting a layoutChanged signal no longer has any effect. I have a proxy model and used setSourceModel() to my TableModel. I set the view's model to the proxy model. I call the layoutChanged signal on my TableView.model().
Here is my simplified code: https://hastebin.com/ofimuzapid
I also read in some forum that it's better design to have the model determine when it needs to layoutChanged. Would you do this by checking say the length of my data_list in either the Model.data() or Model.rowsCount() overriden methods? It seems like that would be worse since it does the check repeatedly. Rather then if I put layoutChanged in my add_task() method like I currently have it, it only "worries" about sending the layoutChanged signal when I add to my data (so only when it needs to).
It's definitely supposed to relay signal to the original model
How did you determine that signal isn't being emitted
I discovered the proxy model emits a dataChanged signal for you. so if I have an item in my table, and I add a new item, the current row will update with the new item's data (so datachanged signal I assume). It isn't until I reload the program (I reload the file where this data is serialized) and the view then shows both items instead of just one.
I hope I worded that okay. I can explain better if you don't know what I mean.
I should mention that I actually don't append to the data list. I insert at index 0.
I personally haven't messed with this much but I remember doing some "hack" to force a view to update.
Since you're subclassing have you followed the guidelines here https://doc.qt.io/qt-5/qabstractitemmodel.html#layoutChanged
Well you did say it works without a proxy
yes. I did not follow that guideline you linked, though. I could try that even though it worked before.
If you try to connect to the layoutchanged signal can you observe that your test slot does not trigger
Both connecting to the proxy and directly to the source model
yes it connects to both
Then the view needs something besides that signal to update?
I'm not sure. There is another problem that might be related. If I enable sorting (self.setSortingEnabled(True)) then I get an attribute error in my proxy model when I override lessThan() https://hastebin.com/sakoyujebe.rb
Have you looked at the left index in such case?
Does it make sense given the current state of the model?
I imagine it's returning none cause it can't find anything at that index
yeah, it's returning none
I didn't put parents as arguments for any of these models because I thought when I use functions such as setModel() it will set the parent. I can try doing that.
Tried it and get the same behavior.
Sorry, I'm not sure what is wrong
Np, I'll take a closer look at what's going on in the rest of my code.
Well I "fixed" my problem but I'm not sure if it's correct to do. I just called the signal to my task_item_model rather than self.model(). So I skip the proxy model when calling the layoutChanged signal.
I fixed the other problem (sorting) by passing Qt.DisplayRole to sourceModel().data()
def lessThan(self, left_: QModelIndex, right_: QModelIndex) -> bool:
left_data = self.sourceModel().data(left_, Qt.DisplayRole)
right_data = self.sourceModel().data(right_, Qt.DisplayRole)
oh teh second problem was something else really stupid of me. Since I was following example I forgot to use python syntax for type() and str() lol
Check youtube @gray warren
I literally just worked my way through some Tkinter examples in Stack Overflow but YouTube tutorials are definitely a better idea
I am trying to get change the Text widgets unfocused selected texts colour however I am getting an error stating that “inactiveselectforeground” is an unknown option.
However, it is documented that it is an option along with “inactiveselectbackground”, “selectbackground” and “selectforeground” which all work.
Here’s some code - on mobile so no text formatting sorry
from tkinter import *
root=Tk()
Text(root, inactiveselectforeground=“red”, inactiveselectbackground=“blue”)
root.mainloop()
Ok, I'm still having trouble. I can't call the layoutChanged signal directly to my model (by bypassing the proxy model) because I then get segmentation faults. I tried a bunch of things, and thought the problem might lie in some other parts of my code. So then I wrote a simple quick program with the same model/view + proxy model structure and I'm having the same issue. Emitting layoutChanged on the proxy model doesn't appear to get to the model, and therefore the view isnt' updated. Here is my basic test program: https://paste.pythondiscord.com/ogifekasim.py
Actually the behavior is better shown by changing line 33 to insert at index 0 instead of append: https://paste.pythondiscord.com/upekahaloy.py
@twilit plinth, it looks like you tried to attach a file type we don't allow. Feel free to ask in #community-meta if you think this is a mistake.
Here is my requirements.txt:
packaging==19.2
pip-review==1.0
pyparsing==2.4.5
PyQt5==5.13.2
PyQt5-sip==12.7.0
six==1.13.0
@twilit plinth https://doc.qt.io/qt-5/qabstractitemmodel.html#layoutChanged
there's a bunch of other stuff that needs to happen before emitting layoutChanged
could be that?
can a tkinter cascade menu appear when hovering, rather than requiring it to be clicked? like how cascades usually work
@proper glade I have tried emitting the layoutAboutToBeChanged signal first which did not solve the behavior. I'm not sure I understand how to use changePersistantIndex(). I tried it by putting in row/column indexes but I'm not quite sure I understand it.
There is this example: https://github.com/baoboa/pyqt5/blob/master/examples/itemviews/customsortfiltermodel.py but it doesn't use an internal data structure. It just adds items "manually" inserting rows.
i dont know enough to help with this, unfortunately
personally i avoid qt's convoluted model stuff and write my own easier to understand pythonic ones
as for your errors
are you sure what you're getting is a segfault?
if youre running the program inside pycharm make sure 'emulate terminal in output console' is checked in the project run config
both pycharm and qt do some weird stuff to stdout/stderr so you might not always see error output without this option enabled
How do I get an image to display on a tkinter canvas with a transparent background?
Does your image have a transparent background?
nvm I sorted it
from tkinter import *
def change():
var.set(var.get()+1)
root.after(1000, change)
root = Tk()
var = DoubleVar()
var.set(0)
t1 = Label(root, text=var.get())
t1.pack()
root.after(1000, change)
mainloop()
Hey, im trying to learn tkinter and dont understand why my label wont change
t1 = Label(root, textvariable=var)
Or something like dat, cant remember exactly and not at pc
But idk if that works with a DoubkeVar :/
If you use classes you can just use the following.
def change():
self.t1.config(text=self.t1text+1)
self.t1text = 0
self.t1 = Label(...)
Thanks i will try it. I thought DoubleVar can change the text label automatically
def draw_ladders(self):
self.squares = {}
odd_ten_list = [[int(str(i) + str(n)) + 1, -1] for i in [(2 * n - 1) for n in range(1, 6)] for n in range(10)]
even_ten_list = [[i, 1] for i in range(1, 101) if [i, -1] not in odd_ten_list]
odd_ten_list = [odd_ten_list[i:i + 10] for i in range(0, len(odd_ten_list), 10)]
even_ten_list = [even_ten_list[i:i + 10] for i in range(0, len(even_ten_list), 10)]
big_list = []
for i in range(10):
if i % 2 == 0:
big_list.append(even_ten_list.pop(0))
else:
big_list.append(odd_ten_list.pop(0))
start_x = 30
for row_num, row in enumerate(big_list):
for number in row:
y_coord = 570 - (row_num * 60)
x_coord = start_x
if number[0] % 10 != 0:
start_x += 60 * number[1]
self.squares[number[0]] = [x_coord, y_coord]
ladders = []
for i in range(5):
start = random.randint(2, 80)
end = random.randint(start+10, 99)
self.ladders.append([start, end])
med = [(self.squares[start][0]+self.squares[end][0])/2, (self.squares[start][1]+self.squares[end][1])/2]
ladder_image = Image.open("clipart-ladder-1.png")
self.canvas.create_image(med, image=ImageTk.PhotoImage(ladder_image))
for some reason the ladders won'r appear
won't*
for i in range(5):
start = random.randint(2, 80)
end = random.randint(start+10, 99)
self.ladders.append([start, end])
med = [(self.squares[start][0]+self.squares[end][0])/2, (self.squares[start][1]+self.squares[end][1])/2]
ladder_image = Image.open("clipart-ladder-1.png")
self.canvas.create_image(med, image=ImageTk.PhotoImage(ladder_image))
it's just that bit that doesnt work
@sudden coral @proper glade I finally figured out the solution to my problem with the proxy model in PyQt. I needed to call beginInsertRows() and endInsertRows() on the QAbstractTableModel before and after I add to my data list. I then needed to call invalidateFilter() on my QTableView.model() (which is set up with a proxy model). No layoutChanged calls involved.
is there any drag and drop gui idle for python?
is it necessary to install visual studio for pyQt5?
I tried by pip install pyQt5 method it work for default IDLE but not for pyCharm...
I want to use pyQt5 in pyCharm
It is not, it is asking for the C++ build tool, not the entirety of visual studio
there is already install some visual studio c++ tool is it not enough for that? 🧐
It is never enough, different cpp version requires different build tool version xd
hmm...thank you
Hello guys
I'm a beginner I'd like to create a Phonebook app using GUI any recommendation?
hi. i want to show my script directory in a treeview in pyqt. i wrote this code but it shows the root dir of OS.
def FilesTreeview(self):
path = os.path.dirname(os.path.realpath(__file__))
self.model = QFileSystemModel()
self.model.setRootPath(path)
self.ui.treeView.setModel(self.model)
self.ui.treeView.setAnimated(False)
self.ui.treeView.setIndentation(20)
self.ui.treeView.setSortingEnabled(True)
hi
good evening developers
i have a question regarding colored output to console
i have been using colorama to color the output to console but it's kinda pain in the ass
i have found blessings and termcolor
what are your opinions on colorama and these options?
any help is appreciated
also, please ping me i have this channel hidden
just tried termcolor, pretty easy to use
it works like this:
from termcolor import colored
print(colored('saki', 'color'))
is there any method for setting QSpinBox values from an array in PyQt5
similar to how you can pass a tuple of values in tkinter's spinbox widget
No. It's designed to increment or decrement a range of integers
You could use like a bidict to map integers to the actual values you want displayed and then override the to and from text methods
That's a bit hacky though
it's doable fairly easily. QSpinBox has a stepBy method you can override.
https://stackoverflow.com/questions/20289468/set-specific-values-in-a-qspinbox
@stray moss
https://paste.pythondiscord.com/ugovagisib.py threw together a python port
only when the buttons are clicked?
yeah
or would you be ok with the procedure being executed if incremented/decremented using mouse wheel?
yes
damn
in any case, you can use stepBy if you're okay with it being called when the mousewheel is used too
stepBy gets called for every increment/decrement
anyone knows some good sources for gtk3 + python
i know for the original site but some up to date videos or other websites would come in handy
Anyone here know much about Kivy? Is there an improvement in speed or something else by using the kv language vs doing everything in python?
I just started using Tkinter and I only see ways to create GUI by first creating a canvas, but how do I create something on my screen without having to create a visible frame behind it
@river flint woah I started tkinter too
I think you put a frame on it
Like a have a master class and then have an initialising function for the master frame
@autumn badge there is no improvement in speed when using kv lang, but it is more convenient in most cases.
You clearly see the structure of the widgets (widget tree). you can use ids
there are also convenient simplifications for binds
Convenience can be very important when creating large applications.
How do you put multiple of the same image onto a tkinter canvas with PIL
this works:
for i in range(5):
start = random.randint(2, 80)
end = random.randint(start+10, 99)
self.ladders.append([start, end])
self.ladder = Image.open("ladder_pa-1.png").resize((45, 30))
self.laddertk = ImageTk.PhotoImage(self.ladder)
self.canvas.create_image(210, 200, image=self.laddertk)
to put on 1 image
but as soon as I indent the last 3 lines, nothing appears
not even the first one
@digital rose Thanks. I will have to dig more into it
I have an app where a lot of labels and items will be generated from data in a json file
What ui library would you recommend for creating something like this? How feasible would it be to use something like Kivy?
@autumn badge Well then adding these widgets from python makes more sense, I think, as it can give you more flexibility
@slender burrow it is 100% possible to do using kivy.
Although I have not tried it yet (create a game), so I can’t name the main difficulties.
First of all you need to find game assets I think)
@digital rose Thanks. Looking at how Kivy scrolls on windows and Mac, I dont know if that will be the best interface for my customers. I think this time I will have to try something else
@autumn badge is something wrong with scroll?
the click/drag doesnt work well with the app i am making. The scroll bar option is not the right implementation fit for my app. I am going to be working with people who are very Windows heavy users and will want more native UI features. I was hoping to use kivy so i could implement the desktop app easily into mobile so they could use the app while on the go (my customers are sales people so being able to use certain apps for their job while out at a location would be super nice)
I understand you. Yes, it may take some time to create more native widgets.
I am working on writing the app in flask, having writen a few apps in QT, tkinter and pysimplegui.
So far, I havent found a UI that i want to stick with
were the libs you used lacking in how they look or ease of writing/understanding it?
@digital rose I've got the assets, I just need to find the right library to help me use them!
lacking int he functionality for windows and mouse using
has anyone here got any recommendations for a scientific GUI for plotting a lot of realtime data/configurations with python?
hello Im trying to get selenium with python to swtich browsers tabs as I was able to get it to create a new tab and go to it but I can not get the program to actually go to the next tab and run code there. Any help?
omg hi @proper glade
sup
is zerorpc the best way to use electron with python?
With PyQt5, what is the standard code structure when __name__ == "__main__"?
Without it, I usually just call main(), but I've seen in other projects that this isn't used for PyQt5
For example, I previously used
import sys
app = QtWidgets.QApplication(sys.argv)
mwindow_agenda = AgendaWindow()
mwindow_agenda.show()
sys.exit(app.exec_())
Yeah that is basically what I use
So how would it work if I'm converting from a non-OOP program to an OOP program? I have a main() function and stuff
You could still move it to a function and then call that from inside the if statement
Like I said, you can put that code in main instead
And just put all the stuff I mentioned above in the main() function, before all the functions are called?
it doesn't matter really, it's just a more stylistic difference
Ah okay
In fact, it's probably better for it to be in a function because that way any variables you need are scoped locally to a function instead of the whole module
Would you say there's anything wrong with this structure (outside of the line lengths which got messed up from indentations)? https://paste.pythondiscord.com/ohosinosoq.py
I'm just trying to go through the process of connecting my current code to the GUI
Yeah I think that's one issue I'm having, because I want to set some labels to have initial values after being calculated in a function
I was using setText() and nothing was happening, so I'll try moving that line to the bottom of main()
app.exec_ will keep the hand until the ui shut
and right after sys exit with the error code of the ui
So I'm having issues with calling the functions from inside the class
Doing the latter would just mean
or subclass Application and handling your data there
Putting the rest of the stuff after sys.exit() into __init__ right?
main is a non problem to me
yes
conceptually it's not great
but it works
Qt is messing with mvc anyway
Okay thank you, I've got it working (somewhat) now
I have this TypeError which I don't really understand
# Predicts future sales of a given beer in a given month.
self.btn_predict.clicked.connect(self.predict_sales(
data_frame, beers, red_helles_growth,
pilsner_growth, dunkel_growth))```
Exception has occurred: TypeError argument 1 has unexpected type 'int'
I don't know why it's erroring since I updated it to work with my UI
when connection you need to give it a function
The only things I've changed for that are getting the user inputs from UI forms instead of manual terminal inputs, and then adding the connection
what you did was call the function
so really you are passing the return value of the function to connect(), rather than the function itself
What you may want is a lambda?
hello gentlemen
like connect(lambda: self.predict_sales(....))
Yeah that works, how does the lambda change the flow of the code?
Like I said, connect() expects a function to be given
Using a lambda here is equivalent to the following
def predict_clicked():
self.predict_sales(data_frame, ...)
# Notice it's predict_clicked and NOT predict_clicked()
self.btn_predict.clicked.connect(predict_clicked)
I find it 50x easier to explain stuff like this over the phone or voice chat here
Yeah maybe but I don't imagine many want to voice chat
chickens :b
Oh okay, thank you, that makes more sense
Is there any downside of using a grid layout and then doing this rather than using a form layout?
It's mainly for convenience but you can read about some of the differences here https://doc.qt.io/qt-5/qformlayout.html#details
Okay thank you
Hello there. I have a question about Pyqt5. How can I add new items (QListWidgeItem) to QListWidget and not removing previous items?
QListWidget.addItem()
@sudden coral well, maybe my code is broken:
FancyListWidget and FancyItemWidget are slightly modifed QListWidget and QListWidgetItem
fancyList = FancyListWidget(self)
fancyList.setAlternatingRowColors(True)
if not fancyList.isVisible():
self._grid.addWidget(fancyList, 0, 0)
# Replace by for file in DataModels.items(sort=...)
for file in files:
fancyItem = FancyItemWidget(self)
fancyItem.setTitle(file)
fancyItem.setDescription(file)
fancyItem.setIcon("empty_box.png", 32, 32)
itemWidget = QListWidgetItem()
itemWidget.setSizeHint(fancyItem.sizeHint())
fancyList.addItem(itemWidget)
fancyList.setItemWidget(itemWidget, fancyItem)
files is list with strings (['file1', 'file2'])
what's the problem here
so
as you can see here : https://doc.qt.io/qt-5/qlistwidget.html#setItemWidget
setItemWidget takes an item and a widget as params
you're providing 2 items I believe
(you said FancyItemWidget was a QListWidgetItem)
(which isn't a QWidget)
I lol'd
looks alright to me, maybe you broke something when overriding some things ?
Hm. Maybe.
you said when you add things, it override the previous ones
Yeah
we're talking like, graphically or with a debugger you see the items being overidden
you sure you're not creating another listview or something ?
In Apps/CloudyFF -> _buildTable
so when you're adding something, you open a dialog box and you retrieve something
and then, you ask for a view update
Yep
but the very first thing you do is removing every widgets and creating another listview
to me, the clearwidget will delete every widgets and their children
and that's why the items are dropped
No, still overrides
try this
put a breakpoint before and after the openfile
and check the addr of the listview, I think the python for this is id (not sure tho)
if the addr isn't the same before and after, the listview is deleted somewhere
or at least replaced by another one
to me, you're creating another (empty) listview each time the buildtable func is called
Another pyqt question: I am using a table view/model. I have a slot that gets executed that enables a button whenever I have one row selected in my table (but not more or less). The problem is the "less" part, as when white space is clicked in the table, there is still an index that is considered selected. I would preferably like the index to be completely deselected but at least be able to tell when a row is not selected.
The table is currently is: setSelectionBehavior(QTableWidget.SelectRows), setSelectionMode(QTableWidget.ExtendedSelection)
I am currently using QTableView.selectedIndexes() to get indexes, then adding the indexes' row to a list to only get how many rows are selected.
ohh I think my problem is that the signal "clicked" doesn't get emitted when whitespace is clicked.
I found the solution: Instead of using QTableView's "clicked" signal, I needed to get a selection model with QTableView.selectionModel() and emit a "selectionChanged" signal from the selection model. So:
QTableView.selectionModel().selectionChanged.connect(my_slot)
Hey hey @twilit plinth I am going through similar problems with pyside2, could you tell me how to do to edit cells in a tableview and save thoose changes
@unique python This example really helped me: https://www.learnpyqt.com/courses/model-views/modelview-architecture/
I had to do things differently because I'm using a QSortFilterProxyModel.
If you have more questions after you have read that example I can try to help.
thank you very much
👍
I think that example it isn't able to help me
I am working with a table and what I need to get saved the data from edited cells in the table view
I solved it with this two things:
def celdasCambiadas(self, topLeft, bottomRight):
if self.modo_boton_editar_guardar == "editar":
return
else:
print(self.model.record(topLeft.row()).value(0))
self.model.updateRowInTable(topLeft.row(), self.model.record(topLeft.row()))
self.db.commit()
And self.model.dataChanged.connect(self.celdasCambiadas)
yo anyone here free to help me out with some stuff?
Hello, so ive been using tkinter to have 6 entries inputs to be appended into a csv file using a button but for some reason I cant get the input of the entries. Could some one help?
invoice = StringVar()
entry_invoice = Entry(root, textvariable=invoice)
customer = StringVar()
entry_customer = Entry(root, textvariable=customer)
date = StringVar()
entry_date = Entry(root, textvariable=date)
recipe = StringVar()
entry_recipe = Entry(root, textvariable=recipe)
gyle = StringVar()
entry_gyle = Entry(root, textvariable=gyle)
quantity = StringVar()
entry_quantity = Entry(root, textvariable=quantity)
def upload_data():
with open('test.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
csv_invoice = invoice.get()
print("1")
print(str(invoice.get()))
csv_customer = str(customer.get())
csv_date = str(date.get())
csv_recipe = str(recipe.get())
csv_gyle = str(gyle.get())
csv_quantity = str(quantity.get())
writer.writerow([csv_invoice, csv_customer, csv_date, csv_recipe, csv_gyle, csv_quantity])
print("New data has been uploaded")
sales_data = Label(root, text="Input New Sales Data", font=("arial", 30, "bold"))
label_invoice.grid(row=1, column=0)
label_customer.grid(row=1, column=1)
label_date.grid(row=1, column=2)
label_recipe.grid(row=1, column=3)
label_gyle.grid(row=1, column=4)
label_quantity.grid(row=1, column=5)
submit_button = Button(root, text="Submit")
so whenever i append the 6 entries
it just appends ",,,,,"
if someone could glance at #help-kiwi when they have a moment i'd appreciate it ❤️ anticipate it being a small mistake thank you
@unique python I see you mean the user edits the tables and you get the data when it's edited. I haven't tried to do that yet so I'm not sure.
Hi, Im making an alarm for for a school project, ive gotten the comparing times finished. I want the window of the "add alarm" to get destroyed when the user presses "save" (to save the alarm). But when i do window.destroy the input doesnt save to the file anymore, does anyone know why?
Code is https://paste.pythondiscord.com/bitupuyonu.py
@echo herald when you call destroy, it destroys that widget (and since it's a window everything inside it). So you'll have to recreate it to show it again. That's pretty pointless though, so instead call window.withdraw() to hide it to the user. deiconify() will show it again. You'll also need to set a "protocol" option so that pressing the "X" button calls your code instead of destroying it:
def on_cancelled():
window.withdraw()
# Do whatever cancelling should do.
window.wm_protocol("WM_DELETE_WINDOW", on_cancelled)
wdym by deiconfig?
sorry im new to python and coding so im a bit confused at everything
😅
i understand everythin until the protocol part
@glacial gust
It's honestly a weird internal TK thing that Tkinter is exposing to you. It's just that the function you provide will be called when the user clicks the X button on the window, instead of destroying it.
window.deiconify() is the name for the "un-minimise" command - turn it back from being an icon on the taskbar.
@echo herald withdraw hides it, deiconify shows it.
The names are terrible, sorry about that.
so it minimizes it?
or it .destroy but without destroying the values
@glacial gust
It hides it completely to the user.
oo cool
iconify() minimises it.
You'll also want to add to your window creating code window.transient(master=your_main_window). This marks it as a child of your main window, so it doesn't appear on the taskbar by itself, is minimised when the main one does, etc.
The protocol method defines a function that is called when you press the X button on the window. Otherwise it'll destroy the widget, which isn't what you want...
o god gimme a sec to process all of this lmao
can i put the protocol in the function?
@glacial gust
I'm not sure what you mean.
The easiest thing to do would just be to do window.wm_protocol("WM_DELETE_WINDOW", window.withdraw).
Put that after you first create the window.
so the window that i want to user to not see is not the main window its a pop up window when the user presses "add" and after the user inputs the time and presses "save" i want the window to disappear.
@glacial gust
Hello guys anyone here using tkinter?
!ask
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.
• 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.
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
@full harbor ^
What exactly regarding Tkinter do you need to know?
Was wondering how to create a new window in tkinter. Could anyone help? Thanks!
@sudden harness what exactly do you mean? The window is the whole application. Do you mean as in different canvas'/frames?
Hey does anyone here use the Pythonista 3 iOS application?
Use a Toplevel widget for a secondary window
Hello, I have a question concrning tkinter. How can I create a Combobox, where you can not input a text.
@round stag sorry for the late reply how can I make the Entry in the center of GUI
@full harbor look into the following: layout managers, weight and sticky. @ me if you read through things and still don’t understand.
@steep bluff ComboBoxes don’t have a text input. Are you sure you’re talking about the right widget?
@steep bluff to prevent users from typing into a Tkinter Combobox, you want to set the "readonly" option on it - that still allows users to select your presets, but not type in custom ones. Use the ttk.Combobox version, then call yourbox.state(['readonly']).
You can still manually set the text value if you want to via code.
Hey do you guys know why
win.unbind_class('Button','<Key-space>')
```Doesn't work?
Here I'm trying to unbind the space key from all the buttons.
I'll just move this to #help-coconut
(pyglet) So I have a problem with my implementation of zooming where the zooming point is allways at the center of the tilemap, is there any way to move it to the center of the screen, or, if possible, implement another method of zooming that doesn't require messing around with opengl?
rendering code can be too big to send through discord (at least through this channel), any better way to send the code?
@echo shell i do wonder how likely it would be for someone to come after me. would i have to disclose the gui framework i use?
If it's just very niche they likely would never even hear about it
Even if they did it's not like they would sue unless it was making very large amounts of money
But if that were the case you would just buy a license
yea
and i think it would be easy enough to swap to pyside from pyqt
still trying to figure out how to install qt 4.8 on my damn mac
Why would you use qt4 when qt5 is out
pyside2 uses qt5
weird, PyQt and PySide2 work on my computer, but every time i load a hello world my computer doesnt see any of the QT modules like QTApplication and QTWidgets
and i have Qt 5.9.2 installed
Then why did you need 4.8? you're trying to use pyside not pyside2?
I don't think you need qt installed anyway for pyside2 to work
because i was looking at pyside
it is weird. I installed pyside2 and pyqt and when i try to import from pyqt.qtwidgets, it doesnt see any of them. I think i need to add some whitelist to my pylint, but last time i did that, my VSC got all screwed up
Did you try to run any code?
Sometimes linters get things wrong
In fact I remember someone else complaining that VSC autocomplete is not working for pyside2
the code works great
it is the linter
its not working for pyqt, pyside2 or wxpython
{
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=PyQt5",
"--extension-pkg-whitelist=PySide2",
"--extension-pkg-whitelist = wx, win32api, win32file, win32process",
"--disable=all",
"--enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode"
]
}```
that is my settings.json file
anything i am doing wrong?
Oh I wouldn't know honestly. I don't use VSC that much.
IIRC I also use flake8 not pylint on there
what IDE do you use?
PyCharm, and even there it's not perfect with pyside2 (I have not tried the other libs)
most things VSC is awesome
but it is some of the things like qt and wx that just dont play well
Basically a lot of people complain https://github.com/mottosso/Qt.py/issues/199
it seems like it happens more with GUI frameworks
ah well, that will be tomorrow ThothLoki's problem
If anyone has extra time and would like to help with the creation of my Jojo bot you can help create stands here https://docs.google.com/document/d/1o4gkz4jmROzNSp79LvOwggQBW2sUI5gZ0Ft6MF2WEPo/edit?usp=sharing
anyone have any opinions on pyglet or enaml?
is there anyway i can drag and draw a circle in tkinter
You'll want to use a tkinter.Canvas along with handling the mouse move and mouse down events
i am drawing a grid first, then a circle on the grid. now i want to change the color of the squares close to the circumference
the only way i see is to redraw the squares but how could i get accurate pixel coordinates for that?
So doing it only around the circumference makes it a bit harder
don't redraw the squares... how are you drawing them originally
when you call create_rectangle it returns a value that identifies the item on the canvas, you can use itemconfig to change the color
so when you initially create them save the id and the pixel coordinates in a list, then you can loop through them and use the coordinates to calculate which ones are close enough to the circle (use pythagorean theorem to determine the distance from the center of the circle)
So to find the positions you can use the following https://stackoverflow.com/a/14829908
From that you can use canvas.find_overlapping(x1, y1, x2, y2) to get the ids that overlap with that area. Then use canvas.itemconfig to modify the properties
this is how i draw it
but thanks for the tip, i am using tkinkter for the first time so i dont know alot
I'm getting a very strange error with Tkinter. I've written a subclass of Toplevel to create tooltips however when I instantiate Toplevel, it throws a "String is not callable" error from setting the master. I've checked that the object that I'm passing in as the master is a Tk instance but I'm still getting the error. At this point I have no idea what's wrong anymore
Here is the relevant code:
https://paste.pythondiscord.com/zodagofura.py
You should have __init__ accept a master which in your case you'd pass window
def __init__(self, master, widget: Widget, text: str=None, getText: Callable=None):
Toplevel.__init__(self, master)
what's wrong with getting master from the widget?
It's not really necessary and you should avoid using private methods prefixed with _ as generally they aren't intended for use outside of the class itself
Does that fix it? If not can you post the full error message
The full error message please
that's the full message
Are you in debug mode?
not that I'm aware of. how do I enable that?
Actually you're in Visual Studio right?
yes
Can you run your script through something else, either cmd or IDLE?
will do
I'd like to see the full error message and I'm not sure how to get that through VS
File "C:\Users\Sam\Desktop\optimisation\GUI.py", line 539, in <module>
page1=inputPage()
File "C:\Users\Sam\Desktop\optimisation\GUI.py", line 288, in __init__
popoutSettings={"var": self.currency, "coords": (240, 150)}, height=2, width=20)
File "C:\Users\Sam\Desktop\optimisation\Modules\Widgets.py", line 176, in __init__
self.tooltip=ToolTip(self.button.master, self.button, getText=lambda: f"State: {self.state}")
File "C:\Users\Sam\Desktop\optimisation\Modules\Widgets.py", line 33, in __init__
Toplevel.__init__(self, master=master)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2342, in __init__
self.title(root.title())
TypeError: 'str' object is not callable```
That should be window.title("Optimisation")
If you are wanting to set the window title to something other than the default
Nw
is it possible to group widgets into one container after they've been instantiated? similar to a <div> element in HTML
You can put them in a Frame if that's what you mean?
Pretty much
So that's the container part sorted. I want to take already instantiated widgets and put them into a Frame. Is that possible ? I think it'd require changing the master which isn't allowed AFAIK
Why do you need to group them? The only reason you need a Frame is to help with the layout of your widgets
And what do you mean isn't allowed?
If I have a group of widgets such as a bunch of RadioButtons or a (Label, Entry) pair, I'd like to create only one instance of my ToolTip class for them. It seems dumb to make 7 instances of ToolTip which are identical apart from their parents
https://stackoverflow.com/questions/6285648/can-you-change-a-widgets-parent-in-python-tkinter sauce for
I think it'd require changing the master which isn't allowed AFAIK
Your tool tip is just a Toplevel widget, why would you need multiple of them for a radio button?
Does anyone here use PyQt?
@analog elbow I do
out of curiosity, what makes QT better than tkinter
besides the amount of lines of code and the qt designer
Widgets and other tools provided by the framework, more customizability, easy native look (when you're focusing on one os)
thanks
now if pyqt or pyside2 would just play nicely with VSC, maybe i would use it
@bleak smelt any good resources for learning how to build desktop apps?
@analog elbow Sentdex on youtube is decent. A lot of what I've learned has been from Stack Overflow and googling examples. Majority of the time you won't find the answer you're looking for, but if you putz around with it long enough, you'll get the result you're looking for.
hm okay thankyou
If you get stuck on something or want an opinion, I've been messing around with PyQt5 for about a year.. I'm FAR from an expert, but I've tried to expose myself to quite a bit.
@thorny spruce sorry for the late response mate.
Your tool tip is just a Toplevel widget, why would you need multiple of them for a radio button?
There are multiple radio button instances and I want each of them to display the same tooltip. For example: everything in the box should have the same tooltip when hovered since they relate to the same subject
It seems a bit silly to create 4 instances of my ToolTip class to allow each of the 4 widgets to have the same tooltip. Instead it makes more sense to me to group them into one instance
You can just pass all of them to your tool tip
I'll try that
i have a numpy array of 415 images, and the coordinates of a rectangular box for each of the 415 images, and I need to plot them in an animation kind of a way
well, doesn't ahve to be a live animation, but atleast the figures should plot one after the other
for i in range(num_frames):
img = frames[:,:,i]
box = bbox[i]
fig, ax = plt.subplots(1)
ax.add_patch(patches.Rectangle((box[0],box[1]),height+1,width+1, linewidth=2,
edgecolor='red',fill=False))
plt.imshow(img)```
i'm doing this,but it throws a warning which says more than 20 images have been opened
fixed it, adding plt.pause(0.1) works
I have a very specific UI related question, I don't want to make anyone mad, and I'm 100% new to discord. Is there a friendly NPC out there willing to help a new character get started without clogging up what seems to be the main chat?
just go ahead and ask your question @ember cedar (probably won't be me though, i need to go in 20 minutes or so)
I know this is a python server, but I'm having a UI issue that has brought my project to a standstill with C# / .NET framework.
@ember cedar There is a C# Discord you can ask in https://discordapp.com/channels/267624335836053506/267624335836053506/654825217843134465
Hello,how can I fix this I put all the jpeg.file in same directory with the python code
i want to know how make a "menu" kind of thing using my own png or jpg files as the buttons. Also i want to know how i can make the graphical stuff for ping pong game. (in python ofc)
pls welp meh
.-.
;w;
There are various options you can use
If you want to program (mostly 2d) games, look into PyGame
tkinter is a GUI interface that comes with Python, so that's another option
i have tried to find how to use tkinter but god i cant get it work..
so i jut have to keep trying ptobably...
until it works
In what way does it not work?
Hello
hi, I'm new and I want to create a game with only python with tkinter module but I don't know where can I learn it -_-. anyone can help me?
tkinter is not great imho, i mean, i did a tetris with it once, i wouldn't want to do something more complex
my preference is kivy, and it works for games, at least 2D ones, but there are other options, like pyglet (but i don't know it at all), or pygame (but i did use it a lot and i don't find it great).
I'm not too good at QT, so this is probably a dumb question... I'm doing this:
self.layout = QtWidgets.QGridLayout()
...
self._loaded_csv = QtWidgets.QLabel("Loaded File: None")
self._load_csv = QtWidgets.QPushButton("Load CSV")
self._refresh_csv = QtWidgets.QPushButton("Refresh CSV")
self._json_output = QtWidgets.QPlainTextEdit(readOnly=True)
self.layout.addWidget(self._load_csv, 0, 0)
self.layout.addWidget(self._loaded_csv, 0, 2)
self.layout.addWidget(self._refresh_csv, 0, 1)
self.layout.addWidget(self._json_output, 2, 0, columnSpan=3)
And columnSpan just does not seem to be working at all
Figured it out....apparently it's positional arguments only, i have to specify it like arg, 2, 0, 1, 3 :/
Hello
I needed help on something
So I'm using Kivy for developing an app
and I'm trying to figure out the kivy syntax for creating code onto a button which will open up the file dialog
(What I mean by this is like an "upload files" button which opens up your files once you click on it)
@digital rose As in, you want to open the file dialog provided by the system (android?)
yes @gloomy mountain
@digital rose the plyer module has a method to open a native file manager
what would you guys recommend for creating complex GUI's in python? tkinter?
no i wouldn't
depending on what you want, i would say Qt if you want a very desktop looking app, or Kivy if you want something much more custom (or if you want your app to work on android/ios as well as desktop).
@celest oriole
thank you! 🙂
@alpine blaze
could you please show me how to use plyer for opening a native file manager
because i've been trying with tkinter
and it doesn't work
I have a button on kivy
@celest oriole yes, but you might need dependencies depending on your os
@digital rose did you look at the plyer documentation?
hang on
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
import tkinter
from tkinter import Frame, Tk, BOTH, Text, Menu, END
from tkinter.filedialog import FileDialog, LoadFileDialog, SaveFileDialog
class StemGrid(Widget, Frame, Tk, Text, Menu, FileDialog):
def onOpen(self):
ftypes = [('Python files', '*.py'), ('All files', '*')]
dlg = filedialog.Open(self, filetypes = ftypes)
fl = dlg.show()
if fl != '':
text = self.readFile(fl)
self.txt.insert(END, text)
def btn(self):
self.onOpen()
class StemApp(App):
def build(self):
return StemGrid()
if __name__ == "__main__":
StemApp().run()
so this is with tkinter and kivy
and i have a separate kv file for my button
there is a kv string in the example
and it doesn't matter, if you understand the example, you should be able to adapt
calling a function is calling a function, whether you do it from python or from kvlang
not good
@digital rose no, that part "doesn't go in your code" it's an example, you have to understand it and adapt it to your code
don't expect to build working software by copying bits of code from here and there and frankeinsteining them together
well, copy the whole example and run it.
it's a one file thing, you can run it standalone
you don't need to edit it at all for that
but you just said a part of it "doesn't go in the code"
i was answering to "so this part goes in the kv file"
which seemed to indicate you wanted to cut some part of the code and put it in a separate file
there is no need for that
I figured out how to use that
@alpine blaze
do you know how to make a button that triggers the file dialog box but not for selecting a file, for saving a file
look at the plyer api, it should be really similar
@alpine blaze
i got it to open up the save file dialog box
but it doesn't let me save as a file type
for two child layouts in a horizontal layout in qt, how would I force them both to occupy half of the parent regardless of their contents?
is it possible to hide the application from the taskbar and "mulitview" ??
I'm trying to remake gyazo... and when opening gyazo it's not showed in the taskbar etc...
you can put it into the tray
oh so then it's not getting showed in both cases ?
@rocky dragon Look into the stretch argument of addWidget
You may need to mess around with the size policy too
Ah you said layout not widget
well there's setStretch maybe that can be applied to layouts too
addLayout also has a stretch arg
hiding that would be really cool 😄
If it has a gui open I think it also needs a taskbar app without some trickery. But being in the tray will allow it to listen to stuff as a script and also have a pop-up gui or other options if that's what you want
I really don't need the gui
it's just for creating a "selection box" so I know which area should be recorded
or is there another way to do that ?
Am I thinking about this window right? Seems a bit complicated with all the layouts https://i.imgur.com/CQF0xaG.png
You may be able to accomplish the same thing with a single grid layout
If you play with the spacing, size policies, etc
I haven't worked on UIs in a while though so I am rusty
I remember those spacer widgets being very useful though - had a bunch of them and would edit the size policy to my liking which was usually enough to do what I wanted
i got it to open up the save file dialog box but it doesn't let me save as a file type
can someone please hlep
Not expecting anyone to resize, but with the grid (on the right) a spacer in the layouts for the double spinner/(x,y,z) combinations pushes the whole grid to the right, so when the window is expanded it leaves a space on the left instead of centering like the combined layouts. Any other way to make one widget occupy all available space in a layout with the other getting its minimum?
https://i.imgur.com/PSliGey.png
set the sizepolicy of one to expanding and the other to minimum?
sorry, was thinking of one thing but wrote another. Meant to stuck it to the left of the label while forcing the label to it's minimum size, keeping the size of the spinner at its default
Not sure off the top of my head. I'd have to try out different size policies for myself to see what, if anything, works
Gonna use the grid since it's a lot simpler with the code at least. Had some meh experiences with it before so didn't even consider using it
PyQT maybe
or Kivy 🙂
Is there any library to make GUI programs for phone
both mentioned above, kivy is simpler I think but didn't try any
What about tkinter?
Not supported on phones, and not a great option anyway
Kivy is fun, you should try it
:)
Kivy:
Can someone tell me how I can change the text in a label in my main window (I have two windows) right when the program is run. I'm using the .kv file. I'm basically trying to make a program that shows the weather and some trees you can plant based on the co concentration in the atmosphere and weather.
Well, you want to change the text attribute of the Label object
What's your issue with doing so?
https://hastebin.com/azociguhaq.py : This is the program file
https://hastebin.com/ubugizaxid.makefile : This is the .kv file
Note: The program uses the geocoder module which gets the user's location (It's to get the weather in the location)
When I didn't have the multiple screens, my code worked fine
but when i added multiple It goes to the default values and doesn't change when the program is run
In the build method, it's supposed to take the Grid() class, change it's values and return that instead of kv but because I'm using mutliple screens, I don't know how to do so.
Gah, don't pass your kv around using a global variable, that's horrendous to read
Oh okay
But anyway, your problem is that you instantiate a Grid() and modify its attributes, then don't do anything with it because you instead display the kv-loaded WindowManager
How do I modify the attributes of the kv-loaded WindowManager?
The simplest solution is: don't, just delete the WindowManager root rule in the kv and construct your simple gui from the build method
Alternatively, don't create a new Grid() and change it, modify the grid of the object returned by Builder.load_file
e.g. give the Grid in your kv rule an id, and access it that way
you mean the """Grid""" under the first """WindowManager""" statement?
Yes
Thank you for your help 😄
I'll try to focus on the readability of my code next time .
Hello, I'm trying to add a custom list widget item with a Thread but It's not working, can you help me?
class QCustomQWidget (QWidget):
def __init__ (self):
super().__init__()
self.textQVBoxLayout = QtWidgets.QVBoxLayout()
self.textUpQLabel = QtWidgets.QLabel()
self.textDownQLabel = QtWidgets.QLabel()
self.textQVBoxLayout.addWidget(self.textUpQLabel)
self.allQHBoxLayout = QtWidgets.QHBoxLayout()
self.iconQLabel = QtWidgets.QLabel()
self.allQHBoxLayout.addWidget(self.iconQLabel, 0)
self.allQHBoxLayout.addLayout(self.textQVBoxLayout, 1)
self.setLayout(self.allQHBoxLayout)
# setStyleSheet
self.textUpQLabel.setStyleSheet('''
color: white;
''')
self.textDownQLabel.setStyleSheet('''
color: gray;
''')
def setTextUp (self, text):
self.textUpQLabel.setText(text)
def setTextDown (self, text):
if text:
self.textQVBoxLayout.addWidget(self.textDownQLabel)
self.textDownQLabel.setText(text)
def setIcon (self, imagePath):
self.iconQLabel.setPixmap(QtGui.QPixmap(imagePath))
This is the custom widget class and I'm calling it with;
for index, name, icon in [(i, "Be aware of his ", "resources\\images\\instruction\\kill.svg")]:
# Create QCustomQWidget
myQCustomQWidget = QCustomQWidget()
myQCustomQWidget.setTextUp(index)
myQCustomQWidget.setTextDown(name)
myQCustomQWidget.setIcon(icon)
# Create QListWidgetItem
myQListWidgetItem = QtWidgets.QListWidgetItem(self.mainQuests)
# Making items unclickable
myQListWidgetItem.setFlags(Qt.NoItemFlags)
# Set size hint
myQListWidgetItem.setSizeHint(myQCustomQWidget.sizeHint())
# Add QListWidgetItem into QListWidget
self.mainQuests.addItem(myQListWidgetItem)
self.mainQuests.setItemWidget(myQListWidgetItem, myQCustomQWidget)
I can create the custom list widget and it's items but can't add item with Thread.
The error is :
QObject::connect: Cannot queue arguments of type 'QVector<int>'
(Make sure 'QVector<int>' is registered using qRegisterMetaType().)
QObject::connect: Cannot queue arguments of type 'QVector<int>'
(Make sure 'QVector<int>' is registered using qRegisterMetaType().)
QObject::connect: Cannot queue arguments of type 'QVector<int>'
(Make sure 'QVector<int>' is registered using qRegisterMetaType().)
QObject::setParent: Cannot set parent, new parent is in a different thread
QObject::installEventFilter(): Cannot filter events for objects in a different thread.
QBasicTimer::start: QBasicTimer can only be used with threads started with QThread
QObject::setParent: Cannot set parent, new parent is in a different thread
QObject::installEventFilter(): Cannot filter events for objects in a different thread.
Any suggestions?
Kivy:
I've been trying to fix it for a while now but I still seem to do it
Here's the edited program file
https://hastebin.com/cagokilego.py: The .py and .kv have been combined into one to make it easier to read
I've made the code a bit nicer in my opinion but It still doesn't do what it's intended to! now it gives me this error:
Traceback (most recent call last):
File "kivy program trial.py", line 80, in <module>
""")
File "C:\Users\Robin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\lang\builder.py", line 399, in load_string
widget = Factory.get(parser.root.name)(__no_builder=True)
File "C:\Users\Robin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\factory.py", line 131, in __getattr__
raise FactoryException('Unknown class <%s>' % name)
kivy.factory.FactoryException: Unknown class <WindowManager>
***Repl Closed***
Hello I have a question is there a way to open a new window after some while loop ? And if yes then how ?
which interface module are you using? Example: Tkinter, Kivy... etc.
PyQt5
Sadly that's a module I haven't learnt yet. Sorry I hope someone assists you.
@pliant pike You're loading the kv before the classes inside it are defined
Load it in your App.build method
Any good way to move from defining GUI in .py to qml?
!ask looking for some guidance, I have a bot in python and want to connect to a flask page that can read variables the bot is writing in realtime.. aka front end showing stock prices and such. is this possible?
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.
• 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.
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
Can someone who knows PyQt5 Thread write me?
Kivy is such a pain sometimes
It takes forever to build android applications with it, so I guess it's only reliable in desktop apps
wxpython is something I would recommend to everyone though. It's easy to learn and runs instantly
I'm not sure what relationship you're inferring between build time and relability
In any case, it takes a few minutes to actually do the compiling for android, subsequent builds just take a few seconds (like less than 10s)
I am very new to python in general.. but I am learning fast and doing good, and now I am trying to learn how to create GUI. What is your advice on what library I should use or you recommend for beginners?
@earnest solar Try C# for GUI. But, if you still want to write it with Python, choose PyQt5 because other ones are pretty old and trash. PyQt5 is also trash but there are docs and a lot of people using it. It's also cross-platform, and If you download the Qt Creator, you can easily make a GUI. Qt Creator is like Visual Studio.
Edit: Also, I think there is no thing like "for beginners" GUI coding for Python. Every one of them is hard lol
@sterile monolith Thanks bro, so C# is the best for GUI.
Kivy is modern and is great for making apps in general
You can see them being showcased here - https://discordapp.com/channels/267624335836053506/658417343407456266/658422019523739667
For stdlib only approach, you also have tkinter as well - no external library / module needed
can tkinter be turned into an android application
Theoretically yes, but doesn't sound like a great experience. You are better off using something that was designed with Android support in mind like Kivy or Qt
(probably ignore any opinion that says only one thing is nice and everything else is trash, it's unlikely they tried and learned enough about the other options to give such a clear cut statement)
last time i did C# was in school, and we had to use that to build UI, and i didn't love it, had at least one case where the api was missing features that i considered basic, and didn't give any way to extend the things, short of gross and very involved hacks)
@alpine blaze I found PyQt5 decent and python is my first ever language. I wouldn't learn C# just to do Gui although I have seen good opinions on it. PyQt5 is well designed and has good support and documentation.
yes, i didn't use it much, but i've heard a lot of good about it, i've been happy with kivy for everything myself, but it's very different, and strong at different things than pyqt/pyside, for conventional desktop applications, pyqt is probably more suited.
lol tshirtman, Firstly I didn't say only one thing is nice, secondly, did you even try WPF C#? Are you guys getting paid for promoting kivy lol
Well it does read that way
if you still want to write it with Python, choose PyQt5 because other ones are pretty old and trash
PyQt5 is also trash
Did you just mean old PyQt versions and not "other ones" as in "every other Python GUI library"
OK fair enough but I think the point still stands to just call so many things "trash" it's pretty dismissive
hey, so im using kivy to do a GUI with multiple windows/screens
but i want to use FloatLayout
and i also want to use the Builder.load.file thing, so how should i format it
class MainWindow(Screen):
pass
class AnalysisWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
kv = Builder.load_file('mt.kv')
class Thingy(App):
def build(self):
return kv```
mores specifically in the build method of Thingy class, what do i write for return
ik if i want to use builder i have to do return kv but if i wanted to do FloatLayout, i have to do return FloatLayout()
The build method should return the widget that you want to be your root widget
It doesn't matter where it comes from, it just matters that that's what it is
If your loaded kv includes a root widget definition, then kv will be assigned to this object, so you can return that
Also, I would do Builder.load_file in the build method on general principle
It avoids getting confused about class definition order
(But it isn't actually necessary, just a clearer way to do things if you want to use the return value, imo)
thanks in advance you can view the code using hastebin>> https://hastebin.com/jacocokudo.py I am having trouble understanding few things on my code using PyQt5 I managed to solve some errors but I don't understand how it is fixed for now .. (excuse me that I am only 3 weeks into programing anyways..) at the functions Buttons , labels, and main_ui. I don't understand why I have to put self. at the begging of my lines I see similar programs for PyQt5 that doesn't have self. at the begging of each line.. so what does it mean and how it reflects on the class next thing I didn't get I getting error before using lambda: at line 40,45 I have done some search and it turns out I have to put single line function lambda to solve this issue why is that.
@sterile monolith i'm one of the contributors to kivy, and i do put some of my money in supporting it, and i have no financial interest in it, it's not a company, it's a project maintained by volunteers in their free time. but if you like c# good for you. Also i do think it was wpf i used, but it's been some time, does the calendar widget still doesn't allow you to highligh a day in a color of your choice, or to bolden more than one day at a time? It's a small thing, but discovering that the only way around that was to do border detection on the result image and manually inject pixels, got me pretty bewildered back then.
@earnest solar What's your question really? What self and lambdas are?
ah ok, thanks @gloomy mountain (sorry for the late reply )
@sudden coral I know what self refers to but I don't understand it's positions in code ... I know lambda is small function but I don't understand why I have to use it there ..at line 40, 45
@earnest solar You don't have to use a lambda (a normal function definition is fine if you want), the real point is that you must pass a function as an argument
@gloomy mountain yes
@earnest solar What alternative are you imagining? Not using a lambda and writing the function call directly?
I write the function directly but it gives me an error.
it doesn't have to be a lambda, you could use functools.partial to be clearer. When you connect a button, it connects it so when you click it, it calls the function object you passed it. so when you pass func it calls func() if you pass lambda : func(arg) it calls the lambda, which in turn calls hte function with the arguments
the lambda isn't needed where you have it, but you musn't call the function
@earnest solar So your problem is, when you write the function directly it does exactly what it says: you run the function that one time
You don't want to do that, you want to tell the code "run this functio when the button is clicked"
That means you must actually give it a function to run
when you call it when passing, it does func()() which is calling the result of func
@earnest solar Consider how this code is actually evaluated
What is the return value of button_choose_folder_click()?
folder_path
So what's that, a filepath as a string?
Then self.button_choose_folder.clicked.connect("C:\some\file\path")
Do you see that?
The code doesn't know what you mean, it only knows what you actually wrote, and since you wrote a function call it runs the function call and effectively replaces it with the return value
I need to understand more give me few mints ..
@gloomy mountain This is how it should work as per Qt doc, self.button_choose_folder.clicked.connect(self.button_choose_folder_click()) but when I do it this way it doesn't run my GUI instead it runs the function as if the button were clicked and this window pop out when I run the code > https://i.imgur.com/zcWleOL.png
!e ```py
def button_choose_folder_click():
return "C:\Documents\file.txt"
function = button_choose_folder_click
print(type(function))
called = button_choose_folder_click()
print(type(called))
@sudden coral :white_check_mark: Your eval job has completed with return code 0.
001 | <class 'function'>
002 | <class 'str'>
@earnest solar This is what inclement was trying to explain
Notice how when the () is added, it calls the function and therefore the type is str instead of function
Qt wants the type to be function
or at least a callable
@sudden coral So if the return of the function```button_choose_folder_click()
No you are missing the point
It wants the function
NOT what the function returns
therefore you cannot call the function there
(unless what you want there, is a callable returned by the function ; but here thats not what you want)
finally I understood this, so it just the () if add them then what ever is there is that is string but Qt is requiring a function instead so removing () then it is a function. thus the better statement will be button_choose_folder.clicked.connect(self.button_choose_folder_click)
pretty much, it allows it to call it when needed/asked to instead. If you need to pass arguments as well, then you would look to lambda or partials
sorry for asking lots of questions .. you can view the code here https://hastebin.com/azaneleraf.rb So my problem is I have connected button Run to butto_run_click at line 49 and when I run the program and click run button the function runs fine but after that the program crash with>> Process finished with exit code -1073740791 (0xC0000409)
The button is working and executing the code at the function but it just crashes after it does that
I just asked a PyQT question on SO, would be great if somebody could help https://stackoverflow.com/questions/59488921/pyqt-qtwebengineview-loads-page-on-windows-but-not-on-macos-using-same-conda-en
another kivy question: let's say i want to do FloatLayout, but with multiple screens
how would i set that up in the .kv file, using ScreenManager
at first i tried doing
class MainWindow(Screen):
pass
class SecondWindow(Screen):
pass
class WindowManager(ScreenManager):
pass``` in the python file and
WindowManager:
MainWindow:
SecondWindow:``` in the kv file
however, the screen doesnt display anything; its just black
So what is your root widget?
sorry i just started kivy yesterday, what is a root widget?
but i did include this part that might be the root widget
class Main(App):
bal = StringProperty(f'{lines[0].strip()}')
def build(self):
return FloatLayout()```
would that be FloatLayout()?
Yes, the root widget is whatever you return from the build method
oh
This widget simply gets drawn filling the window
<MainWindow>:
name: 'main'
FloatLayout:
Label:
text: app.bal
pos_hint: {'left':1, 'top':1}
font_size: 40
size_hint: 0.75, 0.25```
im assuming i did something wrong here, in the .kv file?
Well, what do you want to happen?
i want to use FloatLayout to display a Label with multiple screens
Well, that could mean a few different things in practice, but let's address the immediate problem - you still have the issue that your window is empty?
What is your build method returning?
rn its returning FloatLayout()
Okay, so the problem is simple, FloatLayout doesn't draw anything
oh
What do you want your root widget to be?
the ScreenManager?
class WindowManager(ScreenManager):
pass``` although i set it up as a class
how would i reference it in my build method
If you just want to return any instance of the WindowManager, then do return WindowManager()
If you want to return the root widget rule from your kv file, then return the result of Builder.load_file (I know you had that the other day)
i just tried that but it still shows an empty screen
Well, does the WindowManager() draw anything?
It sounds like your code is fine, you're just displaying widgets that don't draw anything
Try taking a step back and display a Label
Make sure that works
Then put the Label inside your widget tree and see if you can get them to display that way
hmm
MainWindow:
SecondWindow:
<MainWindow>:
name: 'main'
Label:
text: app.bal```
i used this code but its not working
What is the value of app.bal?
its a string that says 1000.00
I mean, let's be sure that there's any text to display :p
i tried using 'test' in place of app.bal, but it doesnt display anything either
Are you 100% sure? For debugging, I'd set it to text: "test" or something
Okay, and what is your root widget now?
wait lemme test again
MainWindow:
SecondWindow:
<MainWindow>:
name: 'main'
Label:
text: 'test'```
doesnt display anythin either
and my root widget is windowmanager
WindowManger()
hmm
Just change WindowManager: to <WindowManager>: in your kv
Forget about root widget kv rules
Do you understand why?
im not entirely sure
but i did remember that something in <> is a parent or root widget?
hi, so i tried programming this "conways game of life" https://en.wikipedia.org/wiki/Conway's_Game_of_Life and i got it to work with a gui, but the gui only updates when i close it any suggestions how to fix it? https://paste.pythondiscord.com/muzavisezi.py (really dont know anything about tkinter - jsut edited a calculater GUI)
uh, the while True loop that creates the gui and run mainloop seems bad, you probably want to do that only once
probably only the CurrentWorld = generation(CurrentWorld) line should be in the loop
and you want a function that can update the window using the CurrentWorld
clearing the frame and then drawing again in it should be fine
how do i do that? xd
well, looking for documentation on the Frame object might help
i forgot how terrible the state of tkinter doc was
there is apparently a grid_forget option to hide widgets from a grid, but i don't know if it clears things propely, maybe it would be easier to keep references to your Labels in a list, and update their bg color depending on the new state
if you want i have a tetris i coded in tk over ten years ago, the source code is half in french and it was before i knew a lot about python, but it still works. 😄 i didn't touch tkinter since
Hey @alpine blaze!
It looks like you tried to attach a file type that we do not allow. We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf.
Feel free to ask in #community-meta if you think this is a mistake.
oh right, no zip
don't take this code as a good example, of python practices, but it knows things i forgot about tkinter (it's played by mouse btw, left/right/middle clicks and wheel to move right/left/rotate and down)
If you want to do something repeatedly without a while True loop then you want to use the .after method
Which is generally in the form of
def step(...):
# single iteration
widget.after(10, step, ...) # schedule again for 10ms
step(...)
Hey, I have a small question I am using PyQt5, I want to position my button at the bottom right corner of the window and I already have horizontal layout. how I can do that the picture explain more. https://i.imgur.com/nlIzGnH.png
Hey i have a big question i want My program to have the user select login or register then i want the program to close that ui and open the one for register or login based on the button click
Use ScreenManager
Is PyInstaller supposed to work when I have multiple python files in one app? Don't know if I'm misunderstanding it, but its not working when trying to build my PyQt5 app..
yes, i did build apps that had dozens of python files with pyinstaller
make sure all of them are either imported when you import main, or referenced in the hiddenimports
If you're on latest pqty version you need to update pyinstaller's pyqt rthook from develop
@rocky dragon thanks for the heads up, im on pyqt 5.14 which seems to be the latest. how do i update the hook?
Importing the python way, just make sure the modules are imported so pyinstaller detects they are used
Copying the code from here to your local pyinstaller copy should work https://github.com/pyinstaller/pyinstaller/blob/bootloader-works/PyInstaller/loader/rthooks/pyi_rth_pyqt5.py
Hello what is wrong with this whenever I remove the columnspan it also make the button separately
separated*
Getting started with Kivy, from @gloomy mountain's website, is a supremely useful collection of learning resources for Kivy: http://inclem.net/2019/12/19/kivy/getting_started_with_kivy/
I have simple question, I have to do these functions #First - Function for identifying files at specific location #Second - Function for checking if the files are already existing at folder location #Third - Function for moving the files to the location
Do I have to make a class for all these functions ? or I just call one by one, Excuse me I am newbie to programming.
Wouldn't need a class. Just separate functions is fine. They should be standalone.
Not sure how this is related to UI though, if you are having trouble try a general help channel.
hi! i want to write a trade manager for poe, similar to mercury trade and I'm wondering which guide framework to use. I want to draw foreground windows that don't have the typical windows look, but are just small frames, like I pasted.
I'm experienced with python, but never created a gui with it, do you have a recommendation for me please?
i'm partial to it, but it seems like kivy would be a great fit, as you can draw the widgets pretty much how you want them
@alpine blaze i'll have a look
@alpine blaze does kivy have any benefit over pyqt5 or something else?
it's more python based, instead of wrapping a c++ api, it's directly built in cython+python, so it's a more pythonic api, it's opengl based, and a thin abstraction over it, so you have a lot of flexibility on that, it's natively multitouch, which makes it more natural on android/ios, also it's available on android/ios.
@alpine blaze ah sounds cool. I only target windows though, so I don't know if I can fully benefit from this. I'll give it a try
Does kivy bind required python libraries during compilation of a project?
can you clarify the question? you don't usually need to build against kivy, the interface is python only, so i think the answer would be no?
Guys I've build an app with tkinter but I was getting windows not responding even though the code was working fine. Did some research and learned that it was caused by loop function I have attached to the button so I tried threading but it's not working... it's calling the functions just when the script starts running.. it's supposed to run after pressing the button. HERE IS MY CODE:
from test2 import *
from tkinter import *
from PIL import ImageTk, Image
import webbrowser
import threading
# Basic Window for GUI
root = Tk()
root.title("Maple")
root.iconbitmap("maple.ico")
root.geometry("400x400")
# Maple Banner
banner = ImageTk.PhotoImage(Image.open("maple_banner.png"))
Label(image=banner).grid(row=0, column=0)
def app(): # Button function
if var.get() == "ZERO":
t1.start()
t2.start()
else:
pass
def callback(event): # Function for callable URL
webbrowser.open_new(event.widget.cget("text"))
# Contents of GUI
var = StringVar()
var.set("ZERO")
Radiobutton(root, text="GAIN CRYSTALS BY FOLLOWING", variable=var, value="ZERO").grid(row=1, padx=120, sticky=W)
Radiobutton(root, text="GAIN CRYSTALS BY LIKING", variable=var, value="ONE", fg="grey").grid(row=2, padx=120, sticky=W)
Button(root, text="START", width=20, command=app).grid(row=3, pady=10)
Button(root, text="END", width=20, command=root.quit()).grid(row=4,pady=5)
Label(root, text="Join the community and learn how to setup the bot").grid()
URL = Label(root, text=r"http://bit.ly/39haqEi-maple", fg="blue", cursor="hand2")
URL.grid()
URL.bind("<Button-1>", callback)
Label(root, text="").grid(pady=10)
Label(root, text="Visit My GitHub for more projects").grid()
URL2 = Label(root, text=r"https://github.com/AVIXASH", fg="blue", cursor="hand2")
URL2.grid()
URL2.bind("<Button-1>", callback)
# End loop
root.mainloop()
this is the main GUI
other dependencies👆
@alpine blaze oh hey, I mean, you can build your stuff with kivy for different platforms, instead of running directly with python, can’t you?
Yes you can, with pyinstaller for example
true tho
I am working on the qualifier for the code jam....I just have a single python file with my function, and at the bottom of it I call my function with various inputs. I am just at the testing functionality phase. So I will just print the result of the called function. ANd it prints fine,but it is different format then I guess calling the function directly from the command line...
So if I use the print for an object, it will just convert it to string? So this is what they got in the description:
datetime.datetime(2019, 12, 16, 0, 0)```
When I run mine as described i get:
2019-12-31 23:12:34
The example is demonstrating its use in a REPL, which represents the datetime object differently than it is when printed.
Point is, the returned object's type needs to be a datime.datetime
Ok..I was just curious as to the difference. If I run it from the prompt I do get:
datetime.datetime(2019, 12, 31, 23, 43, 21)
I havne't done python in years
It uses repr() instead of str() basically
if you did print(repr(parse_iso8601(...))) you should get something similar to the example
When using Kivy how do make a grid and use that grid in screen manager
Hey, I have made pyqt5 app and I take from the user folder_path , how I can save this path for next application startup?
You'll have to save it to your drive, at has the QSettings class for storing on the registry or ini files
Hey all, I am curious about screen resolution effects on the deisgn with PyQt5.
A few months back I got new 4k monitors. As such I have implimented the use of the following code to scale the project properly.
if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
I recently got a laptop with a 1080p monitor and the layout has gotten messed up. Font sizes appear to be either two big or small. The widgets appear to lose their sizing.
I am mixed on if the issue is related to the stylesheet or the snippet above. Any thoughts?
Like are set Font sizes in the stylesheet what is causing the issue? Should I inpliment different style sheets for different resolutions?
Hey, how to do a "partial" clear of the terminal/console/bash? Like, just clearing a certain number of lines. Please ping me if you know, ty!
@glossy hazel you do this with terminal escape codes. The search query you need is 'VT100 escape codes', article here: https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
You can manipulate the cursor with ansi codes over the output otherwise I guess curses which have more magic
[print("*"*10) for _ in range(10)]
print("\u001b[6A")
[print(" "*10) for _ in range(5)]
as an example that clears a half of the first prints
anyone know a good front end framework for creating really professional web ui?
I heard good about bulma (css framework), but didn't try it, and for js logic react and vue are popular options, i'm a bit partial to vue, but react is okay too.
yes, i keep missing occasions to try it, but it does
however
try to work out how to get a container as a navbar to cover the entire top
wouldnt happen to know how to remove the margin?
@alpine blaze sorry for the ping ^
it mentions this:
but im just using html and the provided css link
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
i think?
this certainly means that you can't use the default build, and instead need to do your own
so would i do this in a css file?
and just like my css file too?
ah its not css is it
ive only ever used bootstrap
no, you need to compile the bulma source, after changing this variable, into a a new css, the easiest way is probably sass-cli
and is sass-cli a file?
im totally learning this right now
so i guess by compile, you mean yoink its css from the github, put it into my own and edit the variable
ok, well, i'm not an expert in these things, in web i do more backend than front, but your browser understand css, not scss, (sass), which is a better language, in which bulma is written, so to tweak it, you need to use a converter to go from the sass source to the css version.
yeah, the instructions should get you there step by step
yes, in the end you'll have a css file that you can use with your html file
right
and to make it worse
im actually doing this on my existing website
localhost. but the rest of the site is using bootstrap and all
so i made a quick route, and made a new css file in my static folder
should be fine, i guess
and im using pycharm
xD
its saying choco install sass but im completely lost
am i doing this on my pc's terminal (cmd prompt)
or am i adding an environment variable?
ive found sass in the environment variable list
and its popping an error when i try to install it
fun, for me it says gem install, maybe the page detects i'm on linux and it says choco to you because you are on windows
choco is a package manager for windows
i would say it's unrelated
i need to get powershell?
this is a hell of a lot
how will i even transfer this to a website host
choco is pretty useful for installing stuff like that overall
you won't need to transfer this to your website
