#user-interfaces
1 messages · Page 72 of 1
which ig you can use to scale individual widgets
ig it will remain 30
that is ,scaled too much
Hmmmmm I see
idrk how the width=30 thing works in tkinter
cuz i dont think 30 is number of pixels
I guess my understanding of is wrong somewhere
I think 30 refers to pixels by default, in a button Idk, but usually it would.
hmm
oh alright
Okays, thanks for the help 😄
np :D
oooo
by RiverBank Computing
i suppose you can make mobile apps with pyqt after all
for pyside
hello, can somebody explain me an error message?
Post it
i use buttons and images for a card game ... if i use the method grid_forget no error occurs, but i dont know why 3 of 5 buttons stay on screen and they should disappear ... if i use the method destroy i get at least this error message, but i dont understand it
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.9/tkinter/init.py", line 1892, in call
return self.func(*args)
File "/mnt/linux_d/Python/PyCharmSchnapsenGUINew/main.py", line 383, in <lambda>
command=lambda i=i: player1click(i)))
File "/mnt/linux_d/Python/PyCharmSchnapsenGUINew/main.py", line 32, in player1click
playedcomputercard.configure(image=newimage)
File "/usr/lib/python3.9/tkinter/init.py", line 1646, in configure
return self._configure('configure', cnf, kw)
File "/usr/lib/python3.9/tkinter/init.py", line 1636, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!myownbutton3"
It means the button is destroyed and cannot be reused. Show the code? @leaden tiger
my code is about 450 lines
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hey is there a best practice for developing a GUI for variable screen resolutions?
I've been trying to find the answer too 😦
Currently I am just planning to address it one screen at a time and manually check the 3 primary resolutions.
check the Qt forums
Yeah I will do some research. Just thought I would poke in and ask. I will report back
@tawdry mulch is the code readable?
from tkinter import *
root = Tk()
root.geometry('300x130')
OPTIONS = [
"USD",
"EUR",
"JPY",
"GBP",
"AUD",
"CAD",
"CHF",
"CNY",
"HKD",
"NZD"
] #etc
currencies1 = StringVar(root)
currencies1.set(OPTIONS[0]) # default value
w = OptionMenu(root, currencies1, *OPTIONS)
w.config(font=("Arial Rounded MT Bold", 20))
w.grid(row=0, column=0)
def swap():
cur1option = currencies1.get()
cur2option = currencies2.get()
currencies1 = cur2option
currencies2 = cur1option
swapButton = Button(root, text="Swap", command=swap)
swapButton.grid(row=1,column=0)
OPTIONS = [
"USD",
"EUR",
"JPY",
"GBP",
"AUD",
"CAD",
"CHF",
"CNY",
"HKD",
"NZD"
] #etc
currencies2 = StringVar(root)
currencies2.set(OPTIONS[1]) # default value
w = OptionMenu(root, currencies2, *OPTIONS)
w.config(font=("Arial Rounded MT Bold", 20))
w.grid(row=2, column=0)
This is my code, and I wanna swap options when "Swap" Button is pressed. But it gives me an error when I press instead:
cur1option = currencies1.get()
UnboundLocalError: local variable 'currencies1' referenced before assignment
why is that?
Interesting to see, how I am not alone. I scrolled up to see your issue. I do agree with using Pyside/PyQt for the project over tinker. I am biased though.
I know for my situation I plan to adjust me interface designs to adjust based upon the received screen size. Just a slow approach, got like 15 screens to work on.
Use different variable name
What do you want to swap
There is wayy lot of code
yeah, i told you its about 450 lines 🙂
i checked the buttons which he should hide and he counts 5 buttons ... so normally they should all disappear
What I meant is there are pictures and module that IDH from your code, which wont run. @leaden tiger
what do you mean?
Your code uses pictures and some modules named 'Classes'. Since I dont have those, I cannot run this.
do you want a screenshot?
classes is a different file
i just pasted two files in one paste
1-58 is file classes and the rest is file main
Oh god, should've said it.
Where do you use grid_forget, line number I mean
you should make the cards simpler in my opinion
line 215 and 237
I am sorry, the code is not debuggable. I would recommend you use print() and verify the values and then proceed slowly. @leaden tiger
i already did that :( ... which variables do you mean exactly?
Which all widgets you expect to disappear. Use print() on them and make sure they are accessible?
do you mean print(button)? i checked on those two lines (215 and 237) the buttons which the gui should hide. every computer button appears in command line
Hey I had an idea to make a GUI for viewing pdfs from scratch and also merge multiple pdfs into one. Anyone has any idea for making it happen ?
i'd recommend a logger instead of print
Hello, I am working with pyqt5 and his tools currently and i want when to click a button to go from the current .ui, that i have designed, to another .ui. I achieved that with using stacked widget(widget= QtWidgets.QStackedWidget()) and then widget.addWidget(ui that i want to go) and finally widget.setCurrentWidget(...). The problem was when i went to another python file and imported the widget variable and did the same thing and pops the message "Process finished with exit code -1073740791 (0xC0000409)" (IDE:Pycharm) and then it exits. But when i am working with all my classes in the same file i dont have a problem. Is there any way to solve that? Thanks in advance.
Hmmmm keep debugging IG, I am out of ideas 😦
@tawdry mulch if you want i can send you the pictures in private chat ... i am searching for the error since 1 week
hey anyone knows how t properly remove a widget from a layout ( I am trying to remove every widget from the layout)
for i in reversed(range(self._vbox.count()-1)):
self.layout.removeItem(self.layout.itemAt(i))
# or
self.layout.itemAt(i).widget().setParent(None)
# or
self.layout.itemAt(i).widget().deleteLater()
nothing worked so far (the solutions above do not work)
Make it all into a zip file and send, ill try to debug when im free 🙂
actually doing this rn and this worked perfectly
def clear_attachments(self):
widgets = (self.attached_files_container_widget_layout.itemAt(i).widget() for i in range(self.attached_files_container_widget_layout.count()))
for widget in widgets:
if widget != self.add_file_button:
widget.setParent(None)
@remote ravine please let me know if that works
just starting to play around with pyqt. Trying to have multiple tabs with plots. Currently, my script is plotting all figures under the last created tab. How would one specify a tab to connect each figure to?
I want to swap like if option 1 is USD and option2 is EUR, then when i press the button, option1 becomes EUR and option2 becomes USD
Use config(text=....) rather than switching variables
Follow this @rugged marsh
@tawdry mulch
i tried this....
from tkinter import *
root = Tk()
root.geometry('300x130')
OPTIONS = [
"USD",
"EUR",
"JPY",
"GBP",
"AUD",
"CAD",
"CHF",
"CNY",
"HKD",
"NZD"
] #etc
currencies1 = StringVar(root)
currencies1.set(OPTIONS[0]) # default value
w = OptionMenu(root, currencies1, *OPTIONS)
w.config(font=("Arial Rounded MT Bold", 20))
w.grid(row=0, column=0)
def swap():
print(currencies1.get())
print(currencies2.get())
w.config(text=currencies2)
z.config(text=currencies1)
swapButton = Button(root, text="Swap", command=swap)
swapButton.grid(row=1,column=0)
OPTIONS = [
"USD",
"EUR",
"JPY",
"GBP",
"AUD",
"CAD",
"CHF",
"CNY",
"HKD",
"NZD"
] #etc
currencies2 = StringVar(root)
currencies2.set(OPTIONS[1]) # default value
z = OptionMenu(root, currencies2, *OPTIONS)
z.config(font=("Arial Rounded MT Bold", 20))
z.grid(row=2, column=0)
no errors, but didnt swap too
Hmmmmm why dont you rethink your approach, you are using lists
and then you try to set to a single word
And I recommend using ttk.Combobox.
@rugged marsh
Sure! Ty for the suggestion :)
I just did that for you
from tkinter import *
from tkinter import ttk
root = Tk()
# root.geometry('300x130')
OPTIONS = [
"USD",
"EUR",
"JPY",
"GBP",
"AUD",
"CAD",
"CHF",
"CNY",
"HKD",
"NZD"
] #etc
currencies1 = StringVar(root)
currencies1.set(OPTIONS[0]) # default value
w = ttk.Combobox(root, textvariable=currencies1, values=OPTIONS)
w.config(font=("Arial Rounded MT Bold", 20))
w.grid(row=0, column=0)
def swap():
print(currencies1.get())
print(currencies2.get())
a,b = currencies2.get(),currencies1.get()
currencies1.set(a)
currencies2.set(b)
swapButton = Button(root, text="Swap", command=swap)
swapButton.grid(row=1,column=0)
currencies2 = StringVar(root)
currencies2.set(OPTIONS[1]) # default value
z = ttk.Combobox(root, textvariable=currencies2, values=OPTIONS)
z.config(font=("Arial Rounded MT Bold", 20))
z.grid(row=2, column=0)
root.mainloop()
@rugged marsh
I made a few changes, check again
Tyvm, lemme try runnin it.
IT WORKS!!! THANK YOU SO MUCH!!! @tawdry mulch \
how can i change the size of a dropdown option box in tkinter?
see? the text INSIDE gets out of the box
I'd start by changing the font size to something smaller than what you are using right now.
Did you get it working?
But i dont wanna
Cuz i gotta make it large to match the big screen
I think combobox has a width attribute. Try this:
z = ttk.Combobox(... .. . , width=10)
.. ..
@rugged marsh
Thanks
If that doesnt work you can instead use the expand option in .pack() by saying something like this:
z.pack(side=TOP, fill=X, expand=True)
So that it expands horizontally to fit the size of the screen whenever you resize the window.
You can even say fill=BOTH so it completely resizes, not just horizontally. @rugged marsh
hi
convertButton = Button(root, text="Convert", command=button_command, bg='blue')
convertButton.grid(row=1,column=3)
The code you had originally looked find on a mac
can anyone tell me why the button is still not blue?
?
/wdym
im using a mac, yeah
why???
idk
why not mine???
i just copied and pasted what you posted
hmm, I think you were..
hmm
# Import tkinter
from tkinter import *
ok now this is what i did
w = ttk.Combobox(root, textvariable=currencies1, values=OPTIONS)
what i inserted
it said something about name 'ttk' is not defined
@eager beacon
so add from tkinter import ttk
ok,
just did
w = ttk.Combobox(root, currencies1, *OPTIONS)
TypeError: __init__() takes from 1 to 2 positional arguments but 13 were given
now this
@eager beacon
remove the * from OPTIONS
Yeah I don't know. Maybe the widget containing the combo boxes doesn't have enough room to expand... I don't really use Tk
The code from this post produced the screenshot I sent you
@eager beacon a combobox needs individual elements, removing the * means we are passing an array.
That would throw an error.
don't know what u mean
It doesn't
so... what should i do
run the code from the post above
What do you need help with?
enlarge combobox
^
Use the .pack () instead of grid.
30 works just the same for me 🥲
You can do that only for these three widgets, the two comboboxes and the swap button.
Here, i did it for you.
from tkinter import *
from tkinter import ttk
root = Tk()
# root.geometry('300x130')
OPTIONS = [
"USD",
"EUR",
"JPY",
"GBP",
"AUD",
"CAD",
"CHF",
"CNY",
"HKD",
"NZD"
] #etc
currencies1 = StringVar(root)
currencies1.set(OPTIONS[0]) # default value
w = ttk.Combobox(root, textvariable=currencies1, values=OPTIONS, width=10)
w.config(font=("Arial Rounded MT Bold", 10))
w.pack(side=TOP, fill=BOTH, expand=True)
def swap():
print(currencies1.get())
print(currencies2.get())
a,b = currencies2.get(),currencies1.get()
currencies1.set(a)
currencies2.set(b)
swapButton = Button(root, text="Swap", command=swap)
swapButton.pack(side=TOP)
currencies2 = StringVar(root)
currencies2.set(OPTIONS[1]) # default value
z = ttk.Combobox(root, textvariable=currencies2, values=OPTIONS)
z.config(font=("Arial Rounded MT Bold", 10))
z.pack(side="top",fill=BOTH, expand=True)
root.mainloop()
cant use this code without using pack?
is this not available to grid?
...
Did you run it?
no unfortunately, cuz using pack means i gotta change my whole code literally
You can run this code in a new file
Dont change what you presently have, just run it in a new file.
You can look it up in the docs, its impossible to teach so many arguments within pack. Just briefing you about it:
Pack is just another geometry method to render widgets only, and the arguments i use are:
side, fill, and expand.
padx, pady?
what?
does using pack means i gotta delete all grid stuff?
if yes, so be it, imma learn pack today
I did that for you. Just run my code in a separate file.
This is my code.
this is just my testing code
this is my whole code
ahh no
not this
sorry
this Î
@digital rose
Erm, you just need to this:
widget.grid(.. .. . )
To:
widget.pack(side=TOP, fill=BOTH, expand=True)
Thats all.
You dont need to do anything else.
It would've been better to understand this if you would've run my code there.
No , replace that with the pack statement.
so change all of that?
You can comment it out if you dont want to remove it.
nah imma duplicate my file
Thank god you understood it.
Thats what ive been saying for the past 15 minutes 😆
Thats an example of how you can expand your combobox.
...
Theres no other built-in way, except to just change your font size.
did you ever use windows 3.1?
like ordinary widgets. its better on mac, because they look better than they do on windows, atleast.
oh ok
@rugged marsh i get this on my windows machine, and it does increase the size of the entry in the combo box.
Using mac
i dont really know whats wrong with the size increase on your mac.
different os diff results
mm hmm.
Which Macos version are you using?
@eager beacon does this code work for your mac?
11.0.1
similar to what it does on my windows?
which version of the code?
from tkinter import *
from tkinter import ttk
root = Tk()
# root.geometry('300x130')
OPTIONS = [
"USD",
"EUR",
"JPY",
"GBP",
"AUD",
"CAD",
"CHF",
"CNY",
"HKD",
"NZD"
] #etc
currencies1 = StringVar(root)
currencies1.set(OPTIONS[0]) # default value
w = ttk.Combobox(root, textvariable=currencies1, values=OPTIONS, height=10)
w.config(font=("Arial Rounded MT Bold", 20))
w.pack(side=TOP, fill=BOTH, expand=True)
def swap():
print(currencies1.get())
print(currencies2.get())
a,b = currencies2.get(),currencies1.get()
currencies1.set(a)
currencies2.set(b)
swapButton = Button(root, text="Swap", command=swap)
swapButton.pack(side=TOP)
currencies2 = StringVar(root)
currencies2.set(OPTIONS[1]) # default value
z = ttk.Combobox(root, textvariable=currencies2, values=OPTIONS, height=100)
z.config(font=("Arial Rounded MT Bold", 20))
z.pack(side="top",fill=BOTH, expand=True)
root.mainloop()
this one.
When I increase the font size it forces the combobox to make room for the new font size
let me see
I get this
for the code i just sent?
Yes
They do
@rugged marsh try maximising then. it should fix your problem.
phew! it works finally.
you don't even need to maximize, just increase the size of the window
and run this code @rugged marsh
your solution is the same as (code below), which doesn't work for some reason
for i in reversed(range(self._vbox.count()-1)):
self.layout.itemAt(i).widget().setParent(None)
What are you trying to do?
nvm
for some reason i had to make a tuple first and iterate over it and remove each widget object with self.layout.removeWidget(widget)
weird
@QtCore.pyqtSlot()
def _remove_all_items(self) -> None:
widgets = (self._vbox.itemAt(i).widget() for i in reversed(range(self._vbox.count())))
for widget in widgets:
self._vbox.removeWidget(widget)
seems to work
If you're not going to use the widget again you should call widget.deleteLater() also
so
removing the widget does not delete the widget from memory
sure
@QtCore.pyqtSlot()
def _remove_all_items(self) -> None:
widgets = (self._vbox.itemAt(i).widget() for i in reversed(range(self._vbox.count())))
for widget in widgets:
self._vbox.removeWidget(widget)
widget.deleteLater()
```like this ?
yeah
nope
oki
i aint touching qt6 till KDE (like DE like Gnome) switches to qt6
then you've probably got some time 🙂
no problem
Do you use tkinter? DM! me if you want to join a cool tkinter based server!
is there a way to manipulate a GUI lib to generate multiple input cursors in a text box? i dont need to stick to a particular lib, like tkinter, or PyQT, just wanted to get this done.
Yes those are
Well tk uses the OS default widgets and its event processing system, AFAIK. MAC OS has better UI, so....
@digital rose invite meh in!
There is something similar for grid() too right
@rugged marsh Just post a screenshot of expected result, ill try to recreate it
Hey I'm a bit new out here.
Idk of my question makes a lot of sense but I've been trying to develop an application that can be used on desktop, iOS and Android systems. I ONLY know python as a programming language and want to avoid using html, css javascript throughout the app making process.
Is there a way to do that if I need a decent enough UI/UX interface?
I don't know how to use any of the python frameworks like django, flask, pyqt, Tkinter, etc but would be willing to learn anything that involves python as a programming language
Kivy would be best
you can use PySide or PyQt but uhh
there is not enough documentation on it
if you can learn other stuff, try out Qt Quick
These are the label objects along with some floating point numbers
Okay any idea on how to remove them???
or not include them in a list?
@tawdry mulch
I've been trying to get rid of them in my list for 2 hours now
also they're Label related
not Entry boxes
can we see some code
and what are you trying to do?
Im trying to create multiple labels using loop
def Average_Equation(First, Second, Third, Fourth):
Average_Cell = eval(str((int(Data[First].get())+int(Data[Second].get())+int(Data[Third].get())+int(Data[Fourth].get()))/4))
Average_of_Cells.append(Average_Cell)
print(Average_of_Cells)
for Repeat, Loop in zip(Number_Of_Labels,Average_of_Cells):
Loop.config(text=list(zip(Number_Of_Labels,Average_of_Cells)))
this is what comes out :/
and also
for Repeat in Number_Of_Labels:
Label_4_Average = Label(screen, text=Average_of_Cells, font=('TkDefaultFont', 20, 'bold'))
Average_of_Cells.append(Label_4_Average)
Y_Label += 80
Label_4_Average.place(x=200, y=Y_Label)
This is what I used to actually display
so your trying to make a grid system that lets you place labels inside of the area of the grid?
What do you expect to come? @digital rose
the average of specific numbers
First use print() and verify what Data[First] is then Data[First].get(). @digital rose
Whats the use of adding the @slot decorater ?
how do i set a footer at the top of the tkintr?
Is there anyone who could freeze (compile) the PySide6 project? I think that I can't find any "middle-difficult" solution for this. PyInstaller seems not working with it. FBS is paid. Cxfreeze... Well, I have a mess with it. So isn't there any way to compile my project?
Okay, I somehow made it to work. I don't know which step helped me, but I've done this: upgraded cxfreeze with pip --upgrade cx_Freeze PySide6 (similarly as in cx_freeze PySide2 example on GitHub), move build catalog into the direction without Cyrillic symbols, then I noticed, that it tells about missing .qss file - when I added it into catalog with the executable, then it started working.
If you see the pyside docs they talk about issues with pyinstaller and support for it
Same follows for another new and upcoming tool called nuitka
Pyside is releasing version 6.1 this or next week
And there is supposedly full nuitka support for it
I hope that in the Nuitka case the build will have less size, than in the cx_freeze case. Or tools for reaching less size
Does anyone know how mouseevent flags work in pyside 6? I tried looking at the both dir(event.flags()) and help(event.flags()), and tried reading documentation aswell and doing a bunch of googling, but I can't find anything on how the flags attribute works. The reason I'm trying to figure this out is because I want to get the pos of the mouse click, but all the methods to do so are depreciated except for event.flags(), which supposedly has the details of the event inside of it.
Nevermind, I'm a fool, there's a function for what it inherits called "position()" that does what I need
I'd say PyQt
I've been using tkinter, and most of it i get. However when I try to incorporate classes that create a button or canvas or oval it; it starts falling apart.
Maybe i should avoid using classes? I've been getting overwhelmed at that stage.
can i set up turtle with tkinter?
like setting up the turtle thing on a canvas of tkinter is it possible?
It depends on what you've been doing with your classes. The only thing i literally do is use classes! This is how a small program will look for me in tkinter, every time i start making one from scratch.
from tkinter import *
class Foo(Canvas):
# the class name that is changed everytime.
pass
class MainWindow(Tk):
def __init__(self,):
Tk.__init__(self)
This is a template i use everytime. The way you're incorporating classes could be wrong. It could not be a reason to discard the use of classes.
To let you know, turtle is written in tkinter. So already the screen you are using has a tkinter Canvas embedded in it.
As far as i know, you can only use a Turtle object on a turtle.Screen() instance.
classes are best
Anyone got any tips for making TUIs look good?
You can use a library like Curses, npyscreen (https://npyscreen.readthedocs.io/) or Urwid (http://urwid.org/) to get some nice layouts, widgets and colors.
I made this in Tkinter it is good?
Hi i am making second window in my app, and i cant change variable in Entry (after running the entry is empty, even if there should be "hello")
def new_file(*input):
global filename, textn1, textn2, textn3
window_new = tkinter.Tk()
window_new.title("New File")
filename = askopenfilename()
label1 = tkinter.Label(window_new, text="FileName")
label2 = tkinter.Label(window_new, text="FileExtension")
label3 = tkinter.Label(window_new, text="Description")
textn1 = tkinter.StringVar()
textn1.set("hello")
textn2 = tkinter.StringVar()
textn3 = tkinter.StringVar()
in1 = tkinter.Entry(window_new, textvariable=textn1)
in2 = tkinter.Entry(window_new, textvariable=textn2)
in3 = tkinter.Entry(window_new, textvariable=textn3)
label1.grid(row=0, column=0)
label2.grid(row=1, column=0)
label3.grid(row=2, column=0)
in1.grid(row=0, column=1)
in2.grid(row=1, column=1)
in3.grid(row=2, column=1)
window_new.mainloop()
oh First when you want to make a new window make Toplevel() and not Tk() Tk() should be one in the script
Ok thank you so much 😄 It works now
huh ? nice
when you want to insert text to Entry do.insert(index:int, text:str) :
my_entry.insert(0, "Hello")
and when you want to insert it at the end without int index do:
my_entry.insert(tkinter.END, "Hello")
Oh ok. But maybe i will use tk variables. Idk why but it is more comfortable for me to use.
yes but as the usual way and the best way to insert text to Entry is the .insert(index:int, text:str) function it's made for that 👍🏼
Ok. I will look more into that
keep going in Tkinter 👍🏼
Thanks 😄
you are welcome
I have another problem. I have two listboxes in app (list1, list2) and i have bind on list1 if i select something. But it activates even, if i select something in list2. And function list1.selection_get() returns what i selected in list2 !! pls would you help me?
did you want to call a func when the listbox have focus
I want to call func when i click on element in list1 (left) and another function on element list2 (right) But when i click on list2 list1 function is activated
make tow different functions for list1 : list1.bind("<<ListboxSelect>>", list_1) and list2 : list1.bind("<<ListboxSelect>>", list_2)
or ?
This is function for list1. But idk why it gets called even if i click on the list2
And function for list2 is not done yet. But this was causing errors (thanks god for try: except: XD)
strange did you call it with bind in the another list list2 and you didn't know?
Lol
Hey @tall mesa!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
This is my code. I sent most important parts in screenshots, but i could have missed something.
att؟
your script run like this
Yeah, because it is connecting to my API...
append ?
to the tkinter.Text
idk.. i am new to this
If you are using tkinter.Tk() you need to add
home_text.grid(row=0, column=0)
And also i think Text is wrong command you should use Label (text is used for input as far as i know)
oh ok, ty
did you mean Text the multi line text ? because tkinter.Text is for that
but if you want just output text uneditable use tkinter.Label instead
because
tkinter.Text doesn't have text command like tkinter.Label
it's just multiline input text
also you have "," so it will be syntax error and i think there needs to be root/window too?
Im new to tkinter, but why does this not work?
def accountcreate():
label = tk.Label(text="What would you liek your username to be?")
entry = tk.Entry()
entry.pack()
label.pack()
frame.mainloop()
username = entry.get()
This is outside of that
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')```
what is the Error?
Nothing
It just does nothing
i cant see any problem
It just sits there like a potato
ah
easy
I would suggest to add button to function, where would be entry.get()
or something like that
just cut that frame.mainloop() to the last line of your file
Hmm
Well
That did something
But not the right thing
It now just skips over it
call the function ? accountcreate()
?
Oh
Thats called in another function tho
like:
import tkinter as tk
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')
def accountcreate():
label = tk.Label(text="What would you liek your username to be?")
entry = tk.Entry()
entry.pack()
label.pack()
username = entry.get()
accountcreate()
frame.mainloop()
Uh
More like
from tkinter import *
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')
def accountcreate():
label = tk.Label(text="What would you liek your username to be?")
entry = tk.Entry()
entry.pack()
label.pack()
username = entry.get()
def start():
accountcreate()
start()
frame.mainloop()
your function doesn't have self and self important to work if you use bind
what do you mean by that?
the list1 function dosen't have self parameter
and it's required to work on .bind function
try:
def update_inputs(self, *input):
...
this will work.
I can confirm it does not
this mean your IDE actually have a problem
Im using python idle
Nope. I have *input because of that, so i can use function without arguments too. It is doing the same thing!!
Output:
prints in except
In IDLE you dont need .mainloop()
I mean in original python idle
What do i need?
But this does not seem like original python idle
try this:
import tkinter as tk
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')
def accountcreate():
label = tk.Label(frame,text="What would you liek your username to be?")
entry = tk.Entry()
entry.pack()
label.pack()
username = entry.get()
def start():
accountcreate()
start()
if not working this mean this is not original python idle
Ya it does not work, does the same as before, just skips it over
I have alot more code than that tho
try this if not working your idle have a problem:
import tkinter as tk
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')
def accountcreate():
label = tk.Label(frame,text="What would you liek your username to be?")
entry = tk.Entry()
entry.pack()
label.pack()
username = entry.get()
def start():
accountcreate()
start()
frame.mainloop()
Ahem
It does not work
Ok i am trying to make working code with this i will send it to you
your IDLE have a problem
to fix it
check your python include path
it's important to add bin and lib
How do i do that?
this is working for me:
import tkinter as tk
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')
def accountcreate():
label = tk.Label(frame,text="What would you liek your username to be?")
entry = tk.Entry()
entry.pack()
label.pack()
username = entry.get()
def start():
accountcreate()
start()
frame.mainloop()
did you have windows ?
Yeah
import tkinter as tk
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')
def accountcreate():
label = tk.Label(frame,text="What would you liek your username to be?")
entry = tk.Entry()
button = tk.Button(frame, text="test", command=lambda: print(entry.get()))
entry.pack()
label.pack()
button.pack()
def start():
accountcreate()
start()
frame.mainloop()
This works 100%
go to the search and search for env vars
You have button to test it (print username)
Im there
It does run, but username var is emtpy, because you fill it on start, when entry is empty. That is why it did not work
click on Edit Environment Varibles
yes
but this is not his problem
Ok
I dont think there is problem with env var. Because it is running
His program is running
he sent screenshots did not he?
It does run
Try my code and tell us if it prints right thing
yes
if not you will have a problem with the library
Still skips over it and moves on to the other part of the code @tall mesa
You are running it with another code right? Then there must be error there. Because this is running on my machine and printing that user wrote into entry
There shouldnt be
Wdym , why you make that function?
Can i just send all my code, would make it alot easier to explain
Yeh you can. But with https://paste.pythondiscord.com/
Paste the code there, save and send us the link
your app work well but why you use tkinter if your app just use prints?
Im starting to change it from print to tkinter
Just erase everythink and make it in tkinter. It will be more easy
But the window opens if you do this:
def accountcreate():
frame = tk.Tk()
frame.title("Testing Program")
frame.geometry('400x200')
label = tk.Label(frame,text="What would you liek your username to be?")
entry = tk.Entry()
button = tk.Button(frame, text="test", command=lambda: print(entry.get()))
entry.pack()
label.pack()
button.pack()
username = entry.get()
frame.mainloop()
if os.path.isfile("Users/" + username + '.txt'):
print("You have an account already\n")
login()
else:
password = input("What would you like your password to be?\n")
f = open("Users/" + username + '.txt', "w")
f.write(password)
f.close()
print("Account has been created, please login\n")
login()
but it will not work
oh I will do it and send to you
Ty
and you will take a look at it
yes
not working for me
Is your button a ttk button?
Share some code
There are controllers and frame switching with tkinter available with OOP.
Depends on its purpose really
yeah, this one works tho
I assume you are using multiple instances of Tk(), replace it with Toplevel()
It is useless though
Can you show your import statements?
Seems fine, though the first statement is useless, you can remove it.
What is the problem you are facing?
i want to the button be at the corner
this is what i get
hey guys is possible to call a tkinter function every microsecond instead of a millisecond?
Yes, millisecond*1000 @gritty tree
what should i print instead of the x and y?
isnt that a second? @tawdry mulch u mean ms/1000_
@digital rose It uses rows and columns
Silly me 😉
But I would discourage it though. It might cause slight delay to other events being processed
@tawdry mulch i receive a bad argument error...
Give an example? @gritty tree
window.after(1/500,Lettura())
bad argument "0.002": must be cancel, idle, info, or an integer
Hmm as i thought you cannot pass in decimals
That means the min value that you can pass is 1 microseconds
Less than that is not acceptable
im basically making an oscilloscope with arduino, and i have to read data from it very often with 1ms i can only receive 500hz signal or less
So to answers your question, nope
I see, its not possible I think.
which alternative i have to tkinter?
oh, ty
I don't think there is anything
What do you want to use?
then its possible to create a background software for the GUI? i mean the background software communicate with the arduino while the gui works for itself
Oh you mean in terminal?
Oh sorry my bad, since this UI channel, I thought you were referring to one.
Use if else?
after_idle() would fire up as soon as there is no other task left to process.
it can happens in less than a ms?
It does not take any arguements. As long as there is no events to process. func will be called
I recommend you ask this question on stackoverflow, there might be someway that I am not aware of.
ok thank you
Ill check that out in a min
👍🏼
take input from user? What do you want to display? @digital rose
I dont think you can do this is python. The simplest of loops may take less than an ms, but that's not possible when you're calling a function on top of it.
If you want the user to be re directed to a page, you can create an instance of a Toplevel() (in tkinter.).
Ah.
A naive yet okay-ish approach could be to store the different pages in a dict and clear the terminal at every interval, using something like
os.system('cls')
which is just an example.
Your program structure could look like this:
Take input
Process it
Clear page
Draw new page
@digital rose
And how is this related to UI ? @distant abyss
wrong channel my bad
in tkinter, is there a way to save user inputs as a variable? Everything I can find just uses a throw away function in the Entry command and idk how to use the inputs further downstream.
What im exactly after is to have the initial window ask the user for a filename and a couple other parameters, then based on the loaded data it can open up multiple new windows to display that information. But no idea how to use the user input outside of the command function for said entry
Use global @hybrid spindle
I did 😦 even tried throwing global in every class. Idk maybe im an idiot and forgot how to use global lmao
Shw an exampel?
You can do this with PyQt/PySide2 with QTextCursor inside a QTextDocument

`def load_dat():
global filepath
filepath = datapath_txt.get(1.0,"end-1c")
if filepath:
newWindow = tk.Toplevel(app)
datapath_txt = tk.Text(self,height=3,width=30)
datapath_txt.pack()
pulldat = tk.Button(self,text='Use Path',command=load_dat)
pulldat.pack()
print(filepath)`
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
it always screams at me when i do three🤷♂️
def load_dat():
global filepath
filepath = datapath_txt.get(1.0,"end-1c")
if filepath:
newWindow = tk.Toplevel(app)
datapath_txt = tk.Text(self,height=3,width=30)
datapath_txt.pack()
pulldat = tk.Button(self,text='Use Path',command=load_dat)
pulldat.pack()
print(filepath)
Nothing seems wrong
printing filepath yields ' ' or none.
I suppose I can just make the main program inside that load_dat() function though
are you doing this object oriented?
yupyup
you could use self to store the variable as an attribute of your class? self.filepath = ...
idk if its best practice or not, but when im doing oop i put literally everything within one class or another, and my if __name__ == "__main__" only contains the instance of my class main or similar, and i avoid globals and only use class method locals (ie not self.something) when its a throwaway or temporary variable.
Yeah I think my issue with that is that I'm doing everything on the initialization page or the main app. So it wont wait for user input and immediately tries to execute it. So I did try self, but i think it fails due to the previous statement.
Idk for some reason I struggle with oop and GUI's....probably cause I have virtually no experience with GUIs
Paste the entire code? @hybrid spindle
oop guis can be a right pain to get going with, but once you get past the initial stages and it clicks, youll be making them like its nothing at all
Why is a pain ? 😉 @shrewd raven
to begin with it just doesnt make sense in context of a gui, it gets frustrating especially if you havent done much with oop. but it gets very easy very fast after the initial learning curve
Hmmm OOP is more flexible but if you ask me, I don't use OOP for simple projects at all @shrewd raven
indeed NONE of my projects use OOP
I mean the main projects dont, I use OOP to make widgets though
class App(tk.Tk):
def __init__(self,*args, **kwargs):
tk.Tk.__init__(self,*args,**kwargs)
container = tk.Frame(self)
container.pack(side='top', fill='both', expand=True)
container.grid_rowconfigure(0,weight=1)
container.grid_columnconfigure(0,weight=1)
self.container = container
self.frames = {}
frame = StartPage(container, self)
self.frames = frame
frame.grid(row=0,column=0,sticky='nsew')
self.show_frame(StartPage)
def show_frame(self,cont):
frame = self.frames
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self,parent, controller):
global filepath
tk.Frame.__init__(self,parent)
label = tk.Label(self,text = "File Path", font = LARGE_FONT) #page title
label.pack(pady=10,padx=10)
def load_dat(self):
global filepath
filepath = datapath_txt.get(1.0,"end-1c")
self.filepath = filepath
data = Load(filepath)
print(data.wave)
if filepath:
newWindow = tk.Toplevel(app)
f = Figure(figsize=(8,6),dpi=100)
axes = f.add_subplot(111)
axes.plot([1,2,3,4,5,6,7],[1,2,3,4,5,6,7])
canvas = FigureCanvasTkAgg(f,self)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas,self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
datapath_txt = tk.Text(self,height=3,width=30)
datapath_txt.pack()
pulldat = tk.Button(self,text='Use Path',command=load_dat)
pulldat.pack()
Ideally I'd like to have another class or two similar to StartPage that initializes new windows after the user inputs the filepath. But couldn't figure out how to pass the container to the load_dat() function for it to do this. I'd rather it not open up an entirely new window with TopLevel, but that was all I could get working
just a textbox for the user to input their filename/path. Essentially same as the Label/Entry/Button method to getting user input
I was hoping to avoid using the toplevel and opening a new window. Wanted one overall window and to initialize new windows/ buttons to link to the new windows after the user inputs their information. Unfortunately without toplevel, it wont wait for user input....and reads filepath as empty.
You just want to wait for filepath to be entered or verified?
yeah pretty much thats it. Then integrate this instead of the above:
def load_dat(parent,controller):
global filepath
filepath = datapath_txt.get(1.0,"end-1c")
if filepath:
data = Load(filepath)
frame = PageOne(parent,controller,data)
class Load:
def __init__(self,filename):
data = fits.open(filename)[1].data
self.flux = data['FLUX']
self.wave = data['WAVE']
self.error = data['ERROR']
class PageOne(tk.Frame):
def __init__(self, parent, controller,data):
tk.Frame.__init__(self,parent)
label = tk.Label(self,text = "Species 2", font = LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self,text='Initial Species',
command=lambda:controller.show_frame(StartPage))
button1.pack()
^in place of the toplevel. But right now the "if filepath:" never executes as it evaluates this script before the user actually inputs/verifies? so filepath stays empty and nothing happens
That seems incorrect, in both case it should be same. Try putting print() and ensure the lines that get executed
have. It prints: " filepath= ' ' " immediately upon running and it doesnt wait for me to actually click the button.
but...currently just plowing through it using toplevel and having a complete new window....I guess its not a huge concern.
Ah I think I slightly get you
The thing is usualy, its like we enter the data first and then we execute the function AFTER the data is entered.
Here ig the data is not entered and then load_dat is called and after the if is done it continues
Oh wait that makes no sense. I am dumb
As you said, if print(filepath) prints empty then if filepath NEVER gets executed
yup....unfortunately haha. I mean I dont NEED to do it this way. Just thought itd be a nicer general program if the user could just input their data within the program.
yeahhhh and it immediately executes so its just a no good all around. I found a .wait_window() but I guess I wasn't entering the correct root or placed it wrong as it just disabled all my buttons/labels.
But spent like 6 hours on that problem lol so im just moving on with what I know will work.
If I wasnt dumb I could properly explain my problem....but here we are haha
I'm pretty sure you did it good, I always have trouble reading text and understanding so nvm
a world full of idiots 😅
hi i need help with tkinter how can I switch frames uppon entering a button?
i'm trying to make a mysql crud that can access multiple tables
@digital rose i thought it was me, nvm.
You could try storing the pages in separate functions, and then call them whenever you need to draw a new page. Look at this example:
from os import system
from datetime import datetime as dt
def page1():
print('Welcome!')
def page2():
now=dt.now()
print(f'The date today is,{now.strftime("%d:%M:%Y"}')
pages={
'1':page1,
'2':page2,
}
while True:
page=input('Enter the page number: ')
if page == '1':
system('cls')
pages['1']()
elif page == '2':
system('cls')
pages['2']()
else:
print('invalid page number')
This approach of storing the pages along with their functions in a dict, and calling them later, even though there can be many more solutions to this.
I know we can use themes in tkinter with something like :
self.style.theme_use("classic")
So my question is how can I stop using a particular theme when a button is clicked?
def stop(self,*args):
self.style.stop_using_theme("classic") #?????
B = Button(text="Click me",command = stop)
B.pack()
Try self.style.theme_use("default") inside the func? @pliant dagger
You might want to also say root.update() after it
Okay let me try it out
sure
See my real problem is that I have a button and whenever I click it ,it changes the theme to classic,I also have another button which changes the theme to clam (My script automatically changes the theme to clam when run). So whenever I change the theme to classic it works alright but when I change the theme back to clam it doesn't work only the theme of that particular button gets changed to clam
Check this out
from tkinter import *
from tkinter import ttk
def change():
s.theme_use('default')
root = Tk()
s = ttk.Style()
s.theme_use('vista')
ttk.Label(root,text='Hello').pack()
ttk.Button(root,text='Damn',command=change).pack()
ttk.Button(root,text='Dummy').pack()
root.mainloop()
Poste your code?
that's almost 2k+ lines of code
The relevant parts
ok
def Frontend(self):#User-interface
theme_list = ['Dark theme', 'Light theme']
self.root = Tk()
self.root.tk.call('source','azure-dark.tcl') #Got this theme from github
self.style.theme_use('azure-dark')
self.themebox = ttk.Combobox(self.root, state='readonly', values=theme_list)
self.themebox.current(0)
self.themebox.place(x=640, y=8)
def print_combo(self,*args): #Change to light theme/dark theme here
if self.themebox.get() == 'Light theme':
try:
if not self.called:
self.root.tk.call('source','azure.tcl')
self.called = True
self.style.theme_use("azure")
except Exception as e:
print(e)
if self.themebox.get() == "Dark theme":
try:
#self.style.theme_use("default")
#self.root.tk.call('source','azure-dark.tcl')
self.style.theme_use('azure-dark')
print("Wo")
self.root.update()
except Exception as e:
print(e)
there you go @tawdry mulch , sorry if you don't like mentions
Does any error come out?
nope
That is the only way i get notified
Does the print statement get executed?
yeah it does
the theme of the combobox gets changed
wouldya like to see my screen?
can i get reviews on my ui?
Cool, which language/framework did you use?
pyqt5
Epic!
That is great!
One of the few designs that i actually like.

wow. thats really nice
In terms of style it's quite nice, although in my opinion a different font might be nice. Also, I'm not a huge fan of the input boxes. I think the labels shouldn't disappear when typing, it confuses some people.
It does fit the general modern aesthetic though, and in terms of color/contrast it's really nice.
i do not plan to release it as public software any soon, its for my school project and my teacher dont even how to make this much lmao so i am happy with it for but i will consider your suggestion tho
something similar to Material design?
Not sure if that's specific to Material, I've seen it used a lot when people want to save space in small forms.
i can wait to pull this application together, so much fun making this
my pleasure to hear this sir
how do i loop that to update every minute?
not the right place to ask mate, this is for ui only
sry
np
Take a look at this code snippet, it does something similar to what you want to do and uses .after()
from tkinter import *
from datetime import datetime as dt
class MainWindow:
def __init__(self):
self.master = Tk()
self.renderClock()
self.updateClock()
self.master.mainloop()
def renderClock(self):
self.clockLabel=Label(self.master, text="", font=("Consolas", 15, 'normal'))
self.clockLabel.pack(side=BOTTOM, fill=X, expand=True)
def updateClock(self):
now = dt.now()
t = now.strftime("%d/%M/%Y %H:%M:%S")
self.clockLabel.config(text=t)
self.master.after(999, self.updateClock)
if __name__ == "__main__":
root = MainWindow()
TY!
anyone have issues with pyqt5 just randomly not working? I havent even written any code. Copied an example, ran. Did fine. Ran again, buttons no longer work. Refresh and run...sometimes works sometimes doesnt
idk...my prof told me to use pyqt over tkinter, its "more stable".....first hour and it seems terrible.
He asked this in context of updating a label in tkinter. He even shared a snippet.
@hybrid spindle It seems unlikely that the same code wouldn't work the same way when reloading a new instance of the app.
Are you sure you don't have unsaved changes?
It seems I was impatient....its a slow loader I guess.
He asked for looping so technically it's not ui
No idea why it is wrong to post it here, i thought tkinter was UI ¯_(ツ)_/¯
Tkinter is but he wanted help with looping not tkinter, and If he want to he can ask idc
hey if u made this on ur own, its awesome and fire. Continue making this🔥🔥
Some of it is inspired but yeah did all functions on my own
That is nice, which tutorial? how long have you been working on pyqt? @zenith epoch
I would recommend to reduce the speed down to like 500 ms
For something small/not very complex like that you could use QPainter and just create some widgets and move them into place for the inputs @tawdry mulch
its probably around 100 lines
after() guarantees that it will not call the function BEFORE 999 ms, but there is no guarantee that it will be called exactly at 999, it can be 1000, 1001, 1005, depending upon system and the events to process. @rough isle
Oh that is nice, ill take a look then
Do you know how to use QPainter?
Nope
I jus somehow got Qtcreator to get installed
Is there some special treatment of key events in interactive pyplots within a tkinter program?
It keeps saying my event functions are not defined
not working but got Qt design studio to work @eager beacon
can ya show code?
If that is simple....wat is complex 🤯🤯
I just mean it doesn't have a ton of functionality.. Its all of 2 lineEdits and a pushButton for the user to interact with
give me a few minutes and I'll send you an example
class StartPage(tk.Frame): # start Page can be first 6 images; second page for spillover
def __init__(self,parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self,text = "File Path", font = LARGE_FONT)
label.pack(pady=10,padx=10)
def load_dat():
def onclick(self,event):
toolbar = plt.get_current_fig_manager().toolbar
if event.button==1 and toolbar.mode=='':
window = ((event.xdata-2.5)<=self.wave) & (self.wave<=(event.xdata+2.5))
y = np.median(self.flux[window])
plt.plot(event.xdata,y,'ro',ms=5,pickradius=5,label='cont_pnt',markeredgecolor='k')
plt.draw()
filepath = datapath_txt.get(1.0,"end-1c")
data = Load(filepath)
if len(data.lines) < 7:
newWindow = tk.Toplevel(app)
f = Figure(figsize=(15,8),dpi=100)
for ii in range(len(data.lines)):
self.axesL[ii] = f.add_subplot(6,2,2*ii+1)
self.axesR[ii] = f.add_subplot(6,2,2*(ii+1))
##Plot Stuff##
f.subplots_adjust(left=0.05,right=0.95,top=.95,bottom=0.05,hspace=.2)
canvas = FigureCanvasTkAgg(f,self)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas,self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
#canvas.mpl_connect('button_press_event',lambda event: canvas._tkcanvas.focus_set())
datapath_txt = tk.Text(self,height=3,width=30)
datapath_txt.pack()
pulldat = tk.Button(self,text='Use Path',command=load_dat)#load_dat(parent,controller))
pulldat.pack()
What is this event is it a tkinter generated event? @hybrid spindle
sure
This should give you a good idea about how you can make a UI like that. https://paste.pythondiscord.com/uhudojoses.py
so on left columns, I want to click within the figures to create a list of x and y data that can be used to produce a better polyfit.
I am not sure abt how matplotlib handles tkinter events, hav u tried searcing
You might be better off asking about something like that in a help channel
indeed, unfortunately no luck so far.
Did you get it to work? @tawdry mulch
Which?
This
Oh i did not notice that, just a min
Oooh that looks nice, the colors
There are a lot of presets in QGradient from https://webgradients.com/
Damn okay, ill take a look 😄
@eager beacon thanks!
BTW these coordinates 0, 0, 300, 400 that you used will be same in all screens? Like a different resolution?
Or will the positions change @eager beacon
0,0 is the internal coords of the TopLeft corner of Widget and 300/400 is the width and height of the rects inside the paintEvent in Widget() so the position will always remain in the same position. @tawdry mulch
The only way it could cause an issue is if you didn't resize Widget() to be large enough to contain the rects
Okay cool, thanks
Anyone know why with Tkinter when i close my UI thingy it opens a new one?
then when i close the new one it just closes
- How did you set a line under the input box? A line itself or some stylesheet tweaks?
- What event did you use for the change of colour in the pushbutton?
- How did you add the shadow beneath the button
Great work btw :)
can you share code
import pyautogui as pyg
import keyboard
import tkinter as tk
from core import *
window = tk.Tk()
runningText = "Temp"
for i in range(3):
window.rowconfigure(i, weight=1)
window.columnconfigure(i, weight=1)
label1 = tk.Label(text="Start key",relief=tk.RAISED,borderwidth=5)
label2 = tk.Label(text="Stop key",relief=tk.RAISED,borderwidth=5)
label3 = tk.Label(text="Clicks per second",relief=tk.RAISED,borderwidth=5)
label4 = tk.Label(text=runningText,relief=tk.RAISED,borderwidth=5)
entry1 = tk.Entry()
entry2 = tk.Entry()
entry3 = tk.Entry()
button1 = tk.Button(relief=tk.RIDGE, borderwidth=5,text="Start listening for inputs")
button2 = tk.Button(relief=tk.RIDGE, borderwidth=5,text="Stop Listening for inputs")
label1.grid(row=0,column=0, padx=5,pady=5)
label2.grid(row=0,column=1, padx=5,pady=5)
label3.grid(row=0,column=2, padx=5,pady=5)
label4.grid(row=2,column=0)
entry1.grid(row=1,column=0,padx=5,pady=5)
entry2.grid(row=1,column=1,padx=5,pady=5)
entry3.grid(row=1,column=2,padx=5,pady=5)
button1.grid(row=2,column=1,padx=5,pady=5)
button2.grid(row=2,column=2,padx=5,pady=5)
window.mainloop()```
My first guess ~ core is causing issues. Share its code @regal pulsar
it has nothing but comments currently
When you say from core import *, python runs that file once, so if there is a Tk(), inside that. It can cause issue
I mean just remove from core import * and see
Explanation is here
when i resize the window, the frame does not resize with it
does anyone know why this is happening
I haven't tried yet lel
Stylesheets, pressed property, Pyqt5 graphic property
I will definitely let you guys know about the release, and if you need help making your layout, I would be more than happy to help you
I see python is not the the most probable choice for making desktop apps. What could be the reason for this? and what language / framework is most chosen for making desktop apps for production? i heard electron was popular, though.
Hi i have a question with my code:
so this is my default optionbox, where the options are called currencies1:
"USD - US Dollar",
"EUR - Euro",
"JPY - Japanese Yen",
"GBP - Pound Sterling",
"AUD - Australian Dollar ",
"CAD - Canadian Dollar",
"CHF - Swiss Franc",
"CNY - Renminbi (Chinese Yuan)",
"HKD - Hong Kong Dollar",
"NZD - New Zealand Dollar",
"SEK - Swedish Krona",
"KRW - South Korean Won",
"SGD - Singapore Dollar",
"NOK - Norwegian Krone",
"MXN - Mexican Peso",
"INR - Indian Rupee",
"RUB - Russian Ruble",
"ZAR - South African Rand",
"TRY - Turkish Lira",
"BRL - Brazilian Real"
and i want that if i press a button, the option turns into this:
"USD - 美元",
"EUR - 歐元",
"JPY - 日元",
"GBP - 英鎊",
"AUD - 澳大利亞元",
"CAD - 加拿大元",
"CHF - 瑞士法郎",
"CNY - 人民幣",
"HKD - 港元",
"NZD - 新西蘭元",
"SEK - 瑞典克朗",
"KRW - 韓元",
"SGD - 新加坡元",
"NOK - 挪威克朗",
"MXN - 墨西哥比索",
"INR - 印度盧比",
"RUB - 俄羅斯盧布",
"ZAR - 南非蘭特",
"TRY - 土耳其里拉",
"BRL - 巴西雷亞爾",
I'm doing this on tkinter. how can i acheive this?
flutter is neat
isnt it a google product?
@digital rose can u help me pls
in what?
this
@digital rose
def save_command():
if langOpt.get() == "Chinese":
OPTIONS = [
"USD - 美元",
"EUR - 歐元",
"JPY - 日元",
"GBP - 英鎊",
"AUD - 澳大利亞元",
"CAD - 加拿大元",
"CHF - 瑞士法郎",
"CNY - 人民幣",
"HKD - 港元",
"NZD - 新西蘭元",
"SEK - 瑞典克朗",
"KRW - 韓元",
"SGD - 新加坡元",
"NOK - 挪威克朗",
"MXN - 墨西哥比索",
"INR - 印度盧比",
"RUB - 俄羅斯盧布",
"ZAR - 南非蘭特",
"TRY - 土耳其里拉",
"BRL - 巴西雷亞爾",
] #etc
currencies1 = StringVar(root)
currencies1.set(OPTIONS[0]) # default valu
w = OptionMenu(my_frame1, currencies1, *OPTIONS)
w.config(font=("San Francisco", 25), width=25)
w.grid(row=1, column=0)
saveChangesButton = Button(my_frame2, text="Save", command=save_command, bg='#000080')
saveChangesButton.grid(row=2,column=1)
you can use .config() to update the text, as usual.
OPTIONS = [
"USD - US Dollar",
"EUR - Euro",
"JPY - Japanese Yen",
"GBP - Pound Sterling",
"AUD - Australian Dollar ",
"CAD - Canadian Dollar",
"CHF - Swiss Franc",
"CNY - Renminbi (Chinese Yuan)",
"HKD - Hong Kong Dollar",
"NZD - New Zealand Dollar",
"SEK - Swedish Krona",
"KRW - South Korean Won",
"SGD - Singapore Dollar",
"NOK - Norwegian Krone",
"MXN - Mexican Peso",
"INR - Indian Rupee",
"RUB - Russian Ruble",
"ZAR - South African Rand",
"TRY - Turkish Lira",
"BRL - Brazilian Real",
] #etc
currencies1 = StringVar(root)
currencies1.set(OPTIONS[0]) # default value
w = OptionMenu(my_frame1, currencies1, *OPTIONS)
w.config(font=("San Francisco", 25), width=25)
w.grid(row=1, column=0)
i wanna update the whole options
like changing languages
i dont really get you :/
originally the options are in english
when i press the save button, they become chinese
should i put there?
yes, so that i get to know what variables are used for what purpose.
pep_number
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
where do you want the text to be in chinese?
i mean which widget.
@rugged marsh
its quite strange to see you have declared two OptionMenu widgets with the same name w and over 4 times. Name them something different, so that you can access them to change their text later on, in the command.
Currencies1 and currencies2
At the moment
you can change the text of a StringVar instance by :
var.set(value).
i see currencies1 and currencies2 are StingVars
you want currencies1 to have the value of this table?
ah. i see a second OptionMenu, so im assuming you want the table that is first shown to become:
"USD - 美元",
"EUR - 歐元",
"JPY - 日元",
"GBP - 英鎊",
"AUD - 澳大利亞元",
"CAD - 加拿大元",
"CHF - 瑞士法郎",
"CNY - 人民幣",
"HKD - 港元",
"NZD - 新西蘭元",
"SEK - 瑞典克朗",
"KRW - 韓元",
"SGD - 新加坡元",
"NOK - 挪威克朗",
"MXN - 墨西哥比索",
"INR - 印度盧比",
"RUB - 俄羅斯盧布",
"ZAR - 南非蘭特",
"TRY - 土耳其里拉",
"BRL - 巴西雷亞爾",
from:
"USD - US Dollar",
"EUR - Euro",
"JPY - Japanese Yen",
"GBP - Pound Sterling",
"AUD - Australian Dollar ",
"CAD - Canadian Dollar",
"CHF - Swiss Franc",
"CNY - Renminbi (Chinese Yuan)",
"HKD - Hong Kong Dollar",
"NZD - New Zealand Dollar",
"SEK - Swedish Krona",
"KRW - South Korean Won",
"SGD - Singapore Dollar",
"NOK - Norwegian Krone",
"MXN - Mexican Peso",
"INR - Indian Rupee",
"RUB - Russian Ruble",
"ZAR - South African Rand",
"TRY - Turkish Lira",
"BRL - Brazilian Real"
```?
basically change the table written in english to the chinese version you showed?
@rugged marsh
you can do that by using .config() to change the values in an OptionMenu widget.
what exactly is pyqt5 graphic property
do you have a link?
exactly!
how?
ah, look at this example on how to change the values of an OptionMenu:
from tkinter import *
class MainWindow(Tk):
def __init__(self, ):
Tk.__init__(self, )
self.choices1 = ['Option1', 'Option2']
self.choices2 = ['Option3', 'Option4']
self.draw_widgets()
def switch(self):
self.w['menu'].delete(0, 'end')
self.string_var.set(self.choices2[0])
for i in self.choices2:
self.w['menu'].add_command(label = i, command=lambda:None)
def draw_widgets(self):
self.string_var = StringVar(self)
self.string_var.set(self.choices1[0])
self.w = OptionMenu(self, self.string_var, *self.choices1)
self.w.grid(row = 0, column = 0)
self.change = Button(self, text = 'Change', command=self.switch)
self.change.grid(row=2, column = 0)
if __name__ == '__main__':
root = MainWindow()
root.mainloop()
@rugged marsh
basically making use of the add_command function to add a value, and using .delete() and passing in the indices to delete the contents of the OptionMenu and then inserting the new values.
i got the pressed part, not the shadow one
how do i set stylesheets easily?
Which words? The options in the option menu?
e.g. USD - US dollar, USD=black; -US dollar=grey
heyo so i just made this context menu in pyside2. is there any way to make the context menu have rounded edges?
is there any good libraries for nicer UI in terminal?
electron is famous, python is not jus used for app development. Though there are libraries that can help in the production
how did you make that scrolling view for all the songs?
It's a qtablewidget! :)
and how did you get that acrylic look to the context menu
ah niceee
can you drag and drop each row up and down?
No, not really. Maybe you could but i didn't implement it
i think that is os dependent
Yes
I made a repo specifically for that effect
https://github.com/negated-py/qtacrylic
is translucent windows possible with qt? like blurry bg @modern marsh
noice, its not possible in tkinter, i dont think it is possible in qt either. But that seems far fetched since almost everything is possible with qt
Yes it's just Translucent qmenu
Oops replied to the wrong message there
it looks neat
But yeah it's essentially a Translucent qmenu with acrylic over it
Nice, looks dope
Thanks
I'm aware that i can use qss to modify the look of widgets in qt but i don't know how to make qmenu have rounded edges
hmm
did you try the
border-radius attribute
i love the acrylic but my app is supposed to be crossplatform
guess i gotta make some settings stuff
You could always write a fallback option for your program so that the acrylic only enabled if the app is running on windows machine
try this
how do you guys make separate pages for a UI
do you use different frames or something else?
I am. Just booting up my pc
aight
Didn't do anything
25px
I use QTabWidget
ah
@digital rose u online?
idk how to replace the eng options with chinese :(
i tried (kinda) ur method
but i dont rly get it
ty
Show me the updated code.
Maybe your implementation is wrong.
def close(self, Form):
self.close()
self.pushButton_2.clicked.connect(close)```
i have this and getting error
TypeError: close() missing 1 required positional argument: 'Form'
my class:
class Ui_Form(QtWidgets.QWidget, object):```
can someone help me with tkinter please? i want to do ```py
async def ip(ctx,ip):
this but in tkinter
you called close
without any arguments
so how can call a argument for a pushButton that if it is clicked the whole ui close
self.pushButton_2.clicked.connect(lambda: [self.destroy(), sys.exit()])
close might work too, never tried it
@modern marsh bro thanks alot i have been struggling with this for hours
np
ok
@modern marsh sorry to bother you again, but now when i exit the main application the widget doesnt let the program to end
is this usable with tkinter? Somehow? The widget propery? I am guessing no, but some wild way?
idts
send code
nvm i changed something and now it closes completely, thanks for all your help
np
here is quick showcase of what i made
The UI looks nice, you need to start working on fonts
yes i am first gonna finish up the UI
nice
Well, its all in PyQt
not just that, i am pretty sure if you try hard, something like this is possible with tkinter too
not PERFECT, but something similar
you cant make framelesswindows with tkinter i think
no
but yeah its in pyqt5, althought i worked my ass off to make things work correctly
you used designer?
only for login screen
alright
i am not very familiar with programming yet so had to use it
i know js well enough for discord bots now tho
actaully you can
root.overrideredict(1)
noice then
But, you lose all the controls. The entire taskbar and icons and so on
same in Qt too
i am gonna make custom controls ez
I'm not sure. I rarely use tkinter but i think you could get it work if you can make the tkinter window translucent and somehow get the winId from it.
which is the most powerful gui in python?
Qt
hmm
pyside is qt lol
editor
why are you mixing both
tkinter windows cant be made translucent. Well you can make the whole window transparent, but that does not suffice anything here Ig,
well most of the programs are made in qt if we talk about C++ and python
Well big apps shouldnt be made in python strictly speaking
yea i know
Yeah well as i said I'm not to familiar with tkinter so, sorry i couldn't help you any further
but i have to make this program in python even tho it can get big, cuz i have to stick to my school project guidelines
pfft y'all make guis from qt or other framework? try to make gui from pure opengl and i guarantee you it's fun
i dont have time for that xd, i get those marks now
Which language does OpenGL use?
OpenGL runs natively on cpp and c. Though there's a python binding for OpenGL if you want to try it.
And this is a joke btw dont try to write a gui from scratch using opengl
lol thanks for clarifying
I make a gui for my project with WXPython rn, I'm just started learning gui and just chose wx because it looks nice
Oh and btw qt qml uses OpenGL so technically you've written a gui using OpenGL if you use qml
And that's one of the reason why qml guis usually looks way better than classic qt but then again it's more complex to write
i can do opengl in qt using opengl widget
That means i use OPENGL, huraay
In PyQt5, I'm trying to change the border-image of a button when pressed.
However, it isn't working when I code it.
from PyQt5.QtWidgets import*
from PyQt5.QtGui import*
from PyQt5.QtCore import*
class Main_Window (QWidget):
def __init__(self):
super().__init__()
self.title = "Dice Game"
self.left = 10
self.top = 30
self.width = 420
self.height = 540
self.label = QLabel(self)
self.button_1()
self.mw_attributes()
def mw_attributes(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left,self.top,self.width,self.height)
self.pixmap = QPixmap("C:/Users/nomar/Dropbox/Blueprints/ivc.png")
self.label.setPixmap(self.pixmap)
self.label.resize(self.pixmap.width(),self.pixmap.height())
self.show()
def button_1(self):
pybutton = QPushButton(self)
pybutton.resize(113,53)
pybutton.move(160, 480)
pybutton.setStyleSheet("background:transparent;")
pybutton.setStyleSheet("border-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbutton.png);")
pybutton.clicked.connect(self.clickme)
def clickme(self):
self.setStyleSheet("border-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbuttonpressed1.png);")
app = QApplication(sys.argv) #Creates the app
ex = Main_Window() #Creates the instance of the main window
sys.exit (app.exec_()) #Starts the app```
Here's what the output looks like so far, but the button doesn't change when pushed:
Because when I set it to the background it doesn't look correct.
It actually does work when setting it to a background image first though:
But setting it as a background image has it look like a "sticker" rather than a custom button.
Hey @coarse mirage!
It looks like you tried to attach file type(s) that we do not allow (.kra). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Window background
Button (standard)
button pressed
I just realized that once the button is "unpressed" I'd like it to go back to standard.
This is mainly due to the button looking "strange" when it is set to background image.
Because using background-image has it look strange. Like it's just a sticker. I want the button.png to essentially look like a custom button.
you could use background-color
def button_1(self):
pybutton = QPushButton(self)
pybutton.resize(113,53)
pybutton.move(160, 480)
pybutton.setStyleSheet("background:transparent;")
pybutton.setStyleSheet("background-color : url(C:/Users/nomar/Dropbox/Blueprints/ivcbutton.png);")
pybutton.clicked.connect(self.clickme) ```
you might be able to do pressed/released with it perhaps?
Yeah, but I need the image uploaded to replace the default button.
is the image a plain colour?
Yes. But I'd like to also know how to do it in case it wasn't.
background-image is the only good way to do it
border-image does not set an image for the whole button
Ok now I have this:
pybutton = QPushButton(self)
pybutton.resize(113,53)
pybutton.move(160, 480)
pybutton.setStyleSheet("background:transparent;""background-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbutton.png);")
pybutton.clicked.connect(self.clickme)
def clickme(self):
self.setStyleSheet("background-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbuttonpressed1.png);")```
Better effect. But it still doesn't "press" nor does it change the image pressed.
Not sure I follow.
your image is a plain colour
Question, is the "self.setstylesheet" in clickme setting the style sheet for the entire thing, or just the button?
This gets things working but not only does the image not go back to it's "unpressed" state, but that's not the correct code.
use background-color instead with a rgb color equivalent
do you want it to change colour only on hover?
instead of press
pybutton = QPushButton(self)
pybutton.resize(113,53)
pybutton.move(160, 480)
pybutton.setStyleSheet("background:transparent;""background-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbutton.png);")
pybutton.clicked.connect(self.clickme)
def clickme(self):
self.setStyleSheet("border-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbuttonpressed1.png);")
```
`border-image` is wrong I know.
Ideally I want press.
The color change was to just make it obvious that the image changed to me.
Would it be okay if I contacted you later?
I can understand if you don't want me to.
Don't want to be an inconvience.
I managed to do it. Though in a bit of an odd way.
pybutton = QPushButton(self)
pybutton.resize(113,53)
pybutton.move(160, 480)
pybutton.setStyleSheet("QPushButton""{""background:transparent;""background-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbutton.png);""}""QPushButton:pressed""{""background:transparent;""border-image : url(C:/Users/nomar/Dropbox/Blueprints/ivcbuttonpressed.png);""}")
yes, please do contact me later
please help if you know kivy:
https://stackoverflow.com/questions/67391902/how-to-update-label-text-in-kv-using-properties-in-py
use ids
should I use JS CSS OR HTML for user interfaces???? (or anything else)
all 3 together
how would I do that tho