#user-interfaces
1 messages · Page 71 of 1
expand it?
# getting the canvas size and then expanding image accordingly.
self.canvas_width = self.canvas.winfo_width()
self.canvas_height = self.canvas.winfo_height()
# rendering the image onto the canvas.
self.canvas.create_image(0, 0, self.canvas_width, self.canvas_height)
@proud walrus
i see, thank you! now i can have textures and stuff.
can i just put them on a regular frame or i have to create a canvas? @digital rose
afaik, frame objects are containers and do not render objects on them
oh
plus, it is better to stick with a canvas.
why?
oh. well, i never used the canvas thingy... imma go look at it. thank you for the help
no problem. 👍
Hi ! Do someone know how to stick the "ms" text near the entry box ?
(using tkinter)
Viseur tu es francais non d'ailleurs ?
@digital rose
self.ms_text = Label(window, text = "ms" .. )
self.ms_text.place(x = .. , y = ..)
use .place()
and enter coordinates, according to the cooldown, and delay entry widgets.
je suis "un peu" francais 😅
tricky way, but works as well thanks !
tkinter gui is very weird sometimes
comment ca ?
does place() scale well on resizing the window?
if not how do you adjust it such that it does
Is it possible to create a foldable listbox ?
@modern marsh if you wish to scale a widget along a particular window dimension, use .pack(*args) instead.
widget.pack(side=TOP, expand=True, fill = .. .. )
Now, fill can take in a bunch of arguments, namely X, Y, and BOTH
Which are tk constants.
X allows the widget to scale to fit with the window's maximum horizontal size, Y does that for Vertical, and BOTH fits the widget onto the window.
myLabel.config( text = "the text you want to render now.")
@digital rose
got it
thanks :)
No problem :D
whats wrong with this why wont my tkinter window open
?
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Test button", bg='blue', fg='red')
button.pack()
root.mainloop()
@open lintel the code is fine, check your tkinter installation.
im usign pycharm does this affect it becuase usally i have to go to settings then python interputer then install tkinter but i cannot find tkinter
Try running the same code in IDLE.
PyCharm mustve messed up your tkinter install locations.
Small problem, when the button is pressed it does not shows the message box:
def check_input_widgets_contents(self):
if self.channel_input_data == "":
messagebox.showinfo("showinfo", "Information")
...
starter = Button(self.master, text="Start", command=self.check_input_widgets_contents).grid(row=11, column=1)
but the function is executed
tkinter should be a module over here i think
but i can't find it
Or it will become a None object.
ikr but it does not solve my issue
Small problem, when the button is pressed it does not shows the message box:
def check_input_widgets_contents(self):
if self.channel_input_data == "":
messagebox.showinfo("showinfo", "Information")
...
starter = Button(self.master, text="Start", command=self.check_input_widgets_contents).grid(row=11, column=1)
We dont need the object here
Must be something with channel input data.
And object is starter itself.
the function is executed
oh my bad
the issue is channel ...
Yes.
How do i fix tkinter not working in pycharm
no my tkinter window doces not open
here is the code
root = tk.Tk()
canvas = tk.canvis
button = tk.Button(root, text="Test button", bg='blue', fg='red')
button.pack()
root.mainloop()```
I have a question, I am trying to update an IntVar value and get its value but it does not work, code below:
def set_proxy_checkbox_value(self):
if self.proxy_checkbox_value.get() == 0:
self.proxy_checkbox_value.set(1)
if self.proxy_checkbox_value.get() == 1:
self.proxy_checkbox_value.set(0)
def check_input_widgets_contents(self):
if self.proxy_checkbox_value.get() == 0:
print("unchecked")
else:
print("checked")
...
proxies_checkbox = Checkbutton(self.master, text="Use proxies", command=self.set_proxy_checkbox_value)
proxies_checkbox.grid(
row=5, column=1, sticky=SW
)
self.proxy_checkbox_value.set(0)
The value is still 0...
Please ?
when do i use that ?
So ?
did you not read line 12
I dont think so
bruh
tkinter is built in
you dont need to install it
and it wont show up in your packages
@digital rose maybe you'll be able to help me
Helllo
anyone who has experience with pyqt who can give me advice on how to create a pause and play button in one.
Like these
Where when I click pause it show play vice versa
How did you align those like that :0
Can you please show your code for the layout addition part
Oh :(
you could use a QPushButton
and change the pixmap icon every time you press it
you could subclass a QPushButton and have a boolean indicating the state
I'm thinking how I might do that
how do you do that
if any of you know how please dm me
ill be able to help you tomorrow
Thanks a lot mate take care
var.set('new value')
@digital rose
I fixed alr but thx
anyway to have a system notification in python?
nevermind, i found a working library called notify2
hi guys, i want to use pyqt5, i pip installed pyqt5 and pyqt5-tools
but
pyqt5_tools file incomplete
i tried to reinstall but it doesnt work
im getting this error too
@digital rose There is no such built-in method with turtle. You can use tkinter:
from tkinter import *
from tkinter.messagebox import showinfo
window=Tk()
popup=showinfo('Tkinter', 'Is a GUI lib built in python, inherited from Tcl/Tk languages')
window.mainloop()
how do i install Tkinter?
It is pre installed with python.
how do you install from chrome terminal?
Linux (Beta) is a feature that lets you develop software using your Chromebook. You can install Linux command line tools, code editors, and IDEs on your Chromebook. These can be used to write code, create apps, and more.
@twin rapids im not sure about this, but heres that:
sudo apt-get install python3-tk
Im not sure about this, but might as well try this. Also, not sure if that's tk or tkinter.
oh ok
Sorry, havent dealt much with chromebooks.
No worries.
making a gui is fun.
Hello I have a problem, I am trying to update a label but it does not works (no error):
self.loaded_proxies = Label(self.master, text="Proxies: 0")
self.loaded_proxies.grid(row=10, column=1)
self.loaded_proxies_array.append(proxy)
self.loaded_proxies_count += 1
self.loaded_proxies.configure(text="Proxies: " + str(self.loaded_proxies_count))
@digital rose use textvariable argument instead of text then you can use update_idletasks() method to update the variable
textvariable where ?
on both text ?
textvariable does not works
proxy = StringVar("Proxies : 0")
self.loaded_proxies = Label(self.master, textvariable=proxy)
proxy.set("Proxies : "+ str(proxy_data))
self.loaded_proxies.update_idletasks()
something like that
oh this way
Not working
Here is the code:
load_proxies_button = Button(self.master, text="Load proxies", command=self.load_proxies).grid(row=9, column=1)
self.loaded_proxies_string = StringVar()
self.loaded_proxies_string.set("Proxies: 0")
self.loaded_proxies = Label(self.master, textvariable=self.loaded_proxies_string)
self.loaded_proxies.grid(row=10, column=1)
...
self.loaded_proxies_array.append(proxy)
self.loaded_proxies_count += 1
self.loaded_proxies_string.set("Proxies: " + str(self.loaded_proxies_count))
self.loaded_proxies.update_idletasks
Still no errors but just not working
the code for loading the proxy's running well but yeah still have the issue
@inner nest an idea ?
dont forget the parenthesis of idletasks method
self.loaded_proxies.update_idletasks()
THANK YOU😘😻
Guys I'm new in Python, what would you recommend to build a user interface for my python project?
@split meadow tkinter, it's an easy builtin lib for python : https://docs.python.org/3/library/tkinter.html
Thank you so much!!! I really appreciate this!! 
Learn Tkinter in this full course for beginners. Tkinter is the fastest and easiest way to create the Graphic User Interfaces (GUI applications) with Python. Tkinter comes with Python already, so there's nothing to install!
💻Code: https://github.com/flatplanet/Intro-To-TKinter-Youtube-Course
🎥Course created by Codemy.com. Check out their You...

Anyone use appJar?
i have a gui app using tkinter, but its taking too much cpu and often crashes. thats probably because i have a dynamic clock. what is the best way to make a gui that has dynamically changing labels on screen?
# considering you have a label named MyLabel,
def changeLabelAfter3Seconds():
MyLabel.config(text = "new text")
window_name.after(3000, changeLabelAfter3Seconds)
@fair harness
current_time = datetime.datetime.now().strftime('%H:%M:%S')
clock_lbl = Label(root, font="calibri 60", text=current_time)
clock_lbl.after(999, clock)
clock_lbl.grid(row=0, column=1)
this is my code
what youre doing here, is creating and grid-ing the label after every 1 second.
# do this:
# create the label outside of clock()
clock_lbl = Label(root, font="calibri 60", text="")
clock_lbl.grid(row=0, column=1)
def clock():
current_time = datetime.datetime.now().strftime('%H:%M:%S')
clock_lbl.config(text = current_time)
window.after(999, clock)
use after() with the window, rather than the widget.
@fair harness
so that you update the label, rather than re -create it every second.
i have
then replace window with whatever it is!
Tk() is a window instance after all.
ok!
then say
root.after(999, clock)
thx
i have a similiar block that needs to be updated, i will try to do the same for it
@digital rose it works like a charm!
thanks
no problem. feel free to dm/ping me for any help!
I’m so frustrated with tkinter I’m going to sleep now. But as a quick question, why would root.destroy() cause an infinite spinning icon on my Mac. It acts like it wants to close but never does, so I have to force quite it. It worked once then I closed my laptop and came back to it and it’s not working, code didn’t change. I even tried restarting my laptop. Admittedly I’m using pyenv and changed a line in my Python-build script just to get tkinter working in the first place. I had to point pyenv to my homebrew tcl-tk installation instead of the deprecated system version. I’m feeling like it has dieting to do with pyenv. Do you think I Should redownload the homebrew version?
Something *
i do think this should be the case. you should never tamper with build scripts. it could be an error with the OS itself.
i have seen many people complaining about this, and it usually has to do with the tk version itself. https://www.python.org/download/mac/tcltk/
I’m kinda over pyenv and the issues I have with it what’s an alternative to using different Python versions with different virtual environments.
If you are using macOS 10.6 or later, the Apple-supplied Tcl/Tk 8.5 has serious bugs that can cause application crashes. If you wish to use IDLE or Tkinter, do not use the Apple-supplied Pythons. Instead, install and use a newer version of Python from python.org or a third-party distributor that supplies or links with a newer version of Tcl/Tk.
this is what the docs say.
try sticking to idle for the moment, and at the most, any full fledged editor, probably VS code, so that you have no issues with running your app at the most.
Yeah that’s interesting. Thank you. I just liked pyenv for using different Python versions, but seems like there’s always these weird workarounds with it
I use pycharm
yes. theres no problem with tkinter, its just because of the pre installed python that comes with macOS i think.
you can refer to the link for further help, as I wont be the best help when it comes to MacOS.
Well anyway. Thanks for being a sounding board. Have a great day!
Hello, I have a little problem.
I created a radiobutton and they are two values related to it but somehow when I preset a value it does not works.
Here is the code:
attack_type = StringVar()
follow_attack_type = Radiobutton(self.master, text="Follow", value="Follow", var=attack_type).grid(row=0, column=0)
unfollow_attack_type = Radiobutton(self.master, text="Unfollow", value="Unfollow", var=attack_type).grid(row=0, column=1)
attack_type.set("Unfollow")
hold on
gonna try
AttributeError: 'StringVar' object has no attribute 'current' ??
@digital rose
this does not even exist lol
can someone help me ?
this does not work:
attack_type = StringVar(self.master, "1")
follow_attack_type = Radiobutton(self.master, text="Follow", value="1", var=attack_type).grid(row=0, column=0)
unfollow_attack_type = Radiobutton(self.master, text="Unfollow", value="2", var=attack_type).grid(row=0, column=1)
attack_type.set("1")
please
from tkinter import *
window = Tk()
bar = Canvas()
button = Button(window, border='1.5').place(x = 10, y=10)
bar.create_rectangle(0, 380, 800, 400, fill="#000000")
window.geometry('800x400')
window.resizable(width = False, height = False)
window.mainloop()
why wont it draw a rectange?
You havent created the canvas fully. @twin rapids
Add:
# leave the earlier code unchanged
bar=Canvas(window, height=800, width=800)
bar.pack(side=TOP)
# leave the rest unchanged
Just a suggestion here, do not use .place() in the same line, it makes the widget a None object.
ok
Make them in different lines.
No worries!
why is this a error?
foldersys = Button(window, border="1.5", image = "folder.png", compound = LEFT)
heres my whole code
from tkinter import *
window = Tk()
bar = Canvas(window, height=800, width=800)
button = Button(window, border="1.5", text = "Start")
foldersys = Button(window, border="1.5", image = "folder.png", compound = LEFT)
bar.create_rectangle(0, 350, 800, 400, outline = "#C0C0C0", fill="#C0C0C0")
window.geometry("800x400")
bar.pack(side=TOP)
button.place(x = 10, y = 358)
foldersys.place(x = 30, y = 358)
window.resizable(width = False, height = False)
window.mainloop()
ill just keep it as a text saying files until someone helps me
[Qt] i want to remove the padding between the icons and the top/bottom of the bar
i tried setContentMargins(0, 0, 0, 0) with all related widgets and independently too but to no avail
does anyone know how to fix this?
@ivory ember i need help :P
note that the icon pixmap has been scaled but because of the padding, it does not show as such in the bar
What is the error @twin rapids
https://bpa.st/STBA how to solve this issue?
Traceback (most recent call last):
File "./app.py", line 7, in <module>
foldersys = Button(window, text = "Files",image = "folder.png", border="1.5")
File "/usr/lib/python3.7/tkinter/__init__.py", line 2369, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "/usr/lib/python3.7/tkinter/__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "folder.png" doesn't exist
@digital rose
how?
i dont understand
so you have this files:
proj
|File.py
|folder.png
the actual path is c:\Users\.... so when you type folder.png it's actually not found that file because this is not path this is filename what you want to do tow ways:
- type the full path of
folder.pnglikec:\proj\folder.png - or if you want to make this app find
folder.pngevery where on any pc you will need realtive path and this path will find the python script path then replacefile.pytofolder.pngto make this in codes you will wantoslibrary:
# import the os library so you can edit in paths:
import os
# to get this path folder
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
# to get the folder.png as string will join this folder and folder.png
folder_path = os.path.join(THIS_FOLDER, 'folder.png')
# now set the image path to folder_path:
foldersys = Button(window, border="1.5", image = folder_path, compound = LEFT)
# Done!
so like that way you will get this folder path os.path.dirname(os.path.abspath(__file__)) then join it with folder.png that mean this:(example): c:\proj\folder.png
Hope this will helpful
@twin rapids
whats wrong wit this
import tkinter as tk
HEIGHT = 700
WIDTH = 800
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tk.Frame(root, bg='black')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8
button = tk.Button(root, text="test Button", bg='grey', fg='red')
button.pack()
root.mainloop()
You're missing a closing ) on line 12.
oh yes I didnt see it 👍🏼
where
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8
You forgot an ) at the end
anyone know how to add a clock to the bottom right of the screen like a normal computer
It could be the spacing is still set to the default 12px or that the icon's label is expanded causing it to fill the bar.
Try setting a background color on the label to see whats going on
but how do i do it thats the question
are you trying to create your own OS inside an app?
yea
Tkinter or PyQt?
Tkinter
hmm idk tkinter
I would recommend you use PyQt5
it has a theme that looks like the 90s
also @twin rapids if you use Qt Designer
you can drag and drop widgets to make your UI
i see
but i want to code...
from tkinter import *
window = Tk()
bar = Canvas(window, height=800, width=800)
button = Button(window, border="1.5", text = "Menu")
foldersys = Button(window, text = "Files", border="1.5")
clock = Label(window, text = "Old")
def update():
clock.config(text = "New")
bar.create_rectangle(0, 350, 800, 400, outline = "#C0C0C0", fill="#C0C0C0")
window.geometry("800x400")
bar.pack(side=TOP)
button.place(x = 10, y = 358)
foldersys.place(x = 85, y = 358)
clock.place(x = 0, y = 0)
clock.pack()
clock.after(1000, update)
window.resizable(width = False, height = False)
window.mainloop()
why wont the clock test, text appaer?
Ohh
I will check,thanks :)
your making a music player?
mb, was popping off at a track meet
so you want no padding?
Yeah
Yeah
@modern marsh whats the container widget and button widget (a subclass?)
the icons are placed in QPushButtons and are placed in a QFrame with a QHBoxLayout set in it
@eager beacon i added background colour to the button and it looks like this
so, the icon fits perfectly
but i want padding between button and borders to reduce
o, i did not try to increase the button size lolol
i should try that
@modern marsh Why did it turn the Icon red?
Are you sure you set the background color on the label that contains the pixmap?
Ohh, I just saw you said they were push buttons
yeah i set a stylesheet
so
i increased the button size
and now the padding problem is gone but icon wont scale
play_pause_button.setIcon(qtg.QPixmap(qtg.QImage(ico.PLAY_ICON)).scaled(100, 100, qtc.Qt.KeepAspectRatio))```
how do i set a SizePolicy or something on this 
I thought you wanted the buttons the size they were previously and the black box to be shorter with the icons closer together.
What is your goal?
oh nono
i just want the icons to be as big as possible
in this case, touching the edges of the button (play button)
then you need to use button.setIconSize(QSize(75,75))
The IconSize for the buttons are controlled by the app style you have set or if you haven't set one then its done through the default OS theme.
so you need to manually specify the size to change their size
nice
If you used a label you could have just clicked the setScaledContents(True) and let the OS worry about how many pixels the icon has
PushButtons are typically more trouble than they are worth when you use stylesheets on them
@twin rapids
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("%H : %M : %S")
self.clockLabel.config(text=t)
self.master.after(999, self.updateClock)
if __name__ == "__main__":
root=MainWindow()
Nothing hackish going on here, just used the datetime module to use now() to get current time.
In renderClock() we just create a Label object, that will render the time on the screen.
A tip here, when rendering objects using .pack(), you can say .pack(side=BOTTOM) to render the widget at the bottom of the screen.
And .after() is a magical tool, we just keep on updating the time after every 999 miliseconds, (didnt say 1000ms or 1 second, to give the leverage of 1 ms for the compiler, for any delays.)
and after updating the time, we update the label text, thats it.
@twin rapids
What do you use for Gui's in Python http://www.strawpoll.me/42984402
I use PyQt5 and Kivy
how do i scale my Qt app
i have set a minimum size to it
but when resizing it, the frames dont get resized accordingly
oh nvm that, how do i use anchors in PyQt5
does anyone know a good documentation of tkinter because right now im using https://tcl.tk and its good but it isnt listing all of the attributes for 8.6 like title, config, attributes, etc.
that is literally the best docs for tkinter. what you actually want is comprehensive examples for attribute usage, which is not something for documentations.
ik they're the best docs but they arent listing all of the attributes for each object so i gotta search for a yt video each time i want to see if i can do something
its mainly for tk.Tk() but yea
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/index.html could be a better alternative, it lists attributes by index.
Describes the Tkinter widget set for constructing graphical user interfaces (GUIs) in the Python programming language. Includes coverage of the ttk themed widgets. This publication is available in Web form and also as a PDF document. Please forward any comments to tcc-doc@nmt.edu.
alright ill try it
import tkinter as tk
import pylint as lint
master = tk.Tk()
master.title("blah blh blah")
master.geometry("800x700")
menu_bar = tk.Menu(master)
fileBtn = tk.Menubutton(menu_bar, text="File")
master.mainloop()
why isnt the menu showing up?
nvm im not doing .pack lol
nevermind still not working
can't pack !menu: it's a top level window
@wraith rivet
master.config(menu = menu_bar)
i tried that
ill try again
import tkinter as tk
master = tk.Tk()
master.title("dfcde- untitled")
master.geometry("800x700")
menu_bar = tk.Menu(master)
master.config(menu=menu_bar)
fileBtn = tk.Menubutton(menu_bar, text="File")
menu_bar.pack()
fileBtn.pack()
master.mainloop()
same error
mmm ok
nothing
import tkinter as tk
master = tk.Tk()
master.title("
rfgrfgv - untitled")
master.geometry("800x700")
menu_bar = tk.Menu(master)
master.config(menu=menu_bar)
bar = tk.Menu(menu_bar)
fileBtn = tk.Menubutton(bar, text="File")
master.mainloop()
nothingggg
try this:
import tkinter as tk
import pylint as lint
master = tk.Tk()
master.title("blah blh blah")
master.geometry("800x700")
menu_bar = tk.Menu(master, bg="black")
filemenu = tk.Menu(menu_bar, )
menu_bar.add_cascade(label = "File", menu = filemenu)
master.config(menu = menu_bar)
master.mainloop()
@wraith rivet
menu_bar is a master menu. it does not contain any cascades, like file, edit, etc.
so you need to add cascades to it.
but filemenu is just another menu
filemenu is a child menu.
arent cascades just the dropdown buttons
and why do you need a child menu????
confusing\
its used to render drop down cascades.
mmm ok
you cannot render cascades on a master menu.
i think i might just use swing on jython lol
child menus are like columns in excel. you need them, you cannot do everything on the status bar.
You cannot create menu objects without creating a window instance.
And config to just update the menu used in the window.
Tkinter question:
Why is this text not centered?
label = tk.Label(
text="This is a test",
foreground="white",
background="black"
)
label.place(y=(height/2), x=(width/2))
``` it is slightly off to the right
@ivory ember if you don't mind, can you send a code snippet to explain how exactly QSettings works
The docs are confusing me
Hey, Im using Pyqt to create a GUI but I want my background image to be animated (gif). Does anyone know how I can do so? Here is my current code:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(802, 604)
MainWindow.setStyleSheet(u"background-image: url(:/newPrefix/stars.gif);")```
because the label text have a lot of chars and the center of a widget is in the right so to fix this do in place func x=(width/2)+14)
sorry I'm not good at PyQt5
whats the point in replying?
how do I make this frame the same size as the window?
import tkinter as tk
from tkinter import *
from tkinter import ttk
sub = tk.Tk()
sub.geometry('500x500')
sub.title("red")
sub.configure(bg="red")
my_notebook = ttk.Notebook(sub)
my_notebook.pack(pady=12)
justframe = Frame(my_notebook, width=500, height=500)
justframe.pack(fill="both", expand=1)
framez = Frame(my_notebook, width=500, height=500)
framez.pack(fill="both", expand=1)
my_notebook.add(justframe, text="tab 1")
my_notebook.add(framez, text="tab 2")
mainloop()```
thanks
np
thanks :D
hey
so, i have the same problem rn
i am using a TOML file instead of QSettings temporarily
i just decided rebooting the app would be fine
no
to change the fonts
okay...and?
does this not solve your problem?
i just decided I was fine with rebooting the app
cause I didn't use stylesheets to set it anyways
thx tho
yeah lol
hello, may i ask a question ... i create a card game ... starts with a window and menu and after a click i create a child window with an input box. everything works well, except that my code after the inputbox will be executed after i close the whole programme ... does somebody know why?
ok i found the solution
i need to destroy and quit the window afterwards
@red sequoia :
# see this example:
frameWidth = sub.winfo_width()
frameHeight = sub.winfo_height()
justframe = Frame(my_notebook, width = frameWidth, height=frameHeight)
justframe.pack( .. .. ) # do not change anything here.
# do not change the rest of the code.
Hey guys I have a problem when I am trying to use an icon I get the following error:
_tkinter.TclError: bitmap "icon.ico" not defined
whats the code youre using to render the icon?
@digital rose
root.iconbitmap("icon.ico")
@digital rose :
root.iconbitmap(r'/full/path/to/icon.ico')
remember to add r for raw string.
same 😦
@digital rose
yes?
@digital rose
Same error
show some code.
@digital rose
root.iconbitmap(r"./icon\.ico")
@digital rose
use single quotes instead '
same
its not working
instead of that, try:
root.call('wm','iconphoto',root._w,PhotoImage(file='/path/to/icon.ico'))
@digital rose
it doesnt matter if you say:
root.tk.call() or root.call() both are just aliases of the same .call()command.
its much better than .iconbitmap() which is quite hard to use.
just using the window manager to render an icon.
the frames in the window do not resize with the window
i have set layouts to all frames
and have not set fixed size policies anywhere
does anyone know why the frames wont scale?
[Qt]
@ivory ember do you know why this is happening
no idea ☹
oh alright np
hello
from tkinter import*
import time
import random
import discord
from discord.ext import commands
from tkinter import ttk
from threading import *
root = Tk()
root.geometry("400x400")
def threading():
t1=Thread(target=work)
t1.start()
def work():
client = commands.Bot(command_prefix = "!")
client.run('TOKEN')
Button(root,text="Click Me",command = threading).pack()
root.mainloop()
help ?
Anyone wanting a stylish tkinter theme must check this out!
https://github.com/rdbende/Azure-ttk-theme
whats wrong?
ohh
what?
nice that looks really modern
My panel freezes when I launch the discord bot over the button
first of all, replace client with bot
I want my panel not to freeze when the bot is online
commands.Bot is supposed to be stored in bot
yes
and ?
idk now
the threading isnt working
from tkinter import*
import time
import random
import discord
from discord.ext import commands
from tkinter import ttk
from threading import *
root = Tk()
root.geometry("400x400")
def threading():
t1=Thread(target=work)
t1.start()
def work():
bot = commands.Bot(command_prefix = "!")
bot.run('TOKEN')
Button(root,text="Click Me", command=threading).pack()
root.mainloop()
this is what it should look like
nope
Yeah, it stunned me!
Hope it will help some people here
don't working
@shell kindle I just said its not going to work
@eager beacon
can u help me out with PyQt? im a complete beginner with some python basic knowledge
famous8 told me to ask u for help 👍
amazing theme :D
Good evening, I am French, sooo I apologize in advance for my bad English. (same for my way of writing in python)
I'm using Tkinter and trying to create a loop so i don't have to rewrite every button myself (button "a", button "b", button "c"....). Everything works except for functions created for "command".
#simplified context needed to understand
listeAlphabet=list("abcdefghijklmnopqrstuvwxyz")
def game(x):
print(x)
#[...]
for bouton in listeAlphabet: #"bouton" = "button"
buttonLettre=bouton
if colonne>12:
ligne=1 #"ligne" = "row"
colonne=0 #"colonne" = "column"
buttonLettre=Button(alphabetFrame,text=bouton,command=lambda: game(bouton))
buttonLettre.grid(column=colonne,row=ligne)
colonne+=1
When I run and click on one of the buttons, the terminal necessarily displays: z (the last letter of the list). How do I make sure that when I press the "a" button, it displays a?
AWESOME
but how am i supposed to use this?
@mint dew of what i see, you are creating buttons inside the loop?
exactly
I'm gonna go to sleep now, but leaving this here overnight:
How could I go about making a web dashboard so my bot can be controlled from there?
Please ping me if you can help, hope this doesn't break any rules lol
@mint dew it was quite a weird problem, but do this:
# at the start of the for loop
cmd = lambda i = bouton : game(i)
And now when you create the button:
# in the for loop
buttonLettre(.. .. .. , command=cmd)
.... .. .. ..
#, do not change the rest of the code.
@ripe jetty probably a question for #web-development
Oh thanks, it's working well now 😄
Clearly mentioned in the README.md file
@digital rose Did you have a specific question about PyQt?
No worries.
:(
how can I change titlebar color
Its really not worth the time and effort @neon steppe
🤔 but I want to do this
Do you also want to reimplement the ability to move the window around the screen and be able to minimize/maximize the window?
@neon steppe you just need to add the line below to the init method of whichever window you want to be frameless but after you will need to create a widget for the top of the window to hold the window control buttons that you'll need to set up to close/minimize/maximize the window. you'll also need to write the code in mousemove/mousepress/mouserelease to be able to drag the window around the screen.
self.setWindowFlags(Qt.CustomizeWindowHint | Qt.FramelessWindowHint)
that flag should work for any OS, but if it doesn't work for you, you can remove Qt.CustomizeWindowHint | from the flags method.
Even if you do all of that, the window won't be able to snap into place and resize correctly on Windows when you try dragging it to the to the edge of the screen
Does anybody have a good example of how to do FFT in realtime audio using PyQt/PySide?
Ah I did the custom bars and set up events but the moving around of windows is very wonky
And the frames don't resize with the window :(
Hello, I'm using Tkinter azure theme how do I setup a switch to change from azure dark mode to light mode ?
tag me if you have the answer
I wanna do this through tkinter
@tropic otter I think you're out of luck then 😦
as far as I know thats not possible
root.tk.call('source', 'azure.tcl')
def switch_mode():
if switch.get():
root.tk.call('source', 'azure.tcl')
something like this ?
@digital rose
it is possible. @neon steppe theres not a built in way to do this, but you can do something like this:
from tkinter import *
root=Tk()
root.geometry("400x400+400+40")
ft = ("consolas",10,'normal')
def changeTitleBarConfig():
root.overrideredirect(1) # disables default window manager config
titleBarFrame = Frame(root, height=80, width=100)
titleBarFrame.pack(side=TOP, anchor=NE, expand=False)
exitButton = Button(titleBarFrame, text="x", fg="white", bg="red",padx=12, pady=4,bd=0,relief="sunken",
font=ft,command=lambda:root.destroy())
exitButton.pack(side=RIGHT)
changeTitleBarConfig()
root.mainloop()
it just creates a window with a close button, but of course you can go much farther with this.
quite simple, by overriding the window manager, to disable the default window borders, and then created a frame on top of the window to hold the exit button.
hi, so i have a gui made with tkinter that opens a window that plays a pygame game
how do i make it so that when i close the pygame window without closing the tkinter window
im using pygame.quit and exit() to close the game
@digital rose Nice! Can you make it so you can drag the window with the mouse?
The exit button doesn't seem to work for me
it works, for me at least.
weird, it just drops focus when I press the button
probably something to do with macos
yeah, it is a kind of windows - oriented program, and so the button style.
@digital rose 🤔 its my laptop problem
hello, may i ask a question ... is it possible if i create 2 buttons ... that i assign 1 button to another?
lol got it
i mean is it possible to say button A = button B with images and commands? ... because if i create a new button ... the new button has a different number and thats a problem in my application
I'm trying to make the A* pathfinding algorithm with tkinter. does anyone know how i can search for neighbour canvases? each square is a class
@abstract crown its doesnt make sense to render individiual canvas as a single square. Instead, you can create a grid of lines, and use a function to get a neighboring cell:
# assuming that you have each cell's info as [row, column]
def neighbour(cell):
return [cell[0]+1, cell[0]-1,cell[1]+1,cell[1]-1]
This should return the 4 neighbours of the cell.
By the way, i recently made a flood fill visualiser, making use of the same technique, the 4 direction approach to render neighbouring cells on the canvas.
( i do have a gif showing flood fill in action on my app.)
how should i make the cells?
def createGrids(self):
for x in range(0, self.SW, 20):
for y in range(0, self.SH, 20):
print(x,y)
square = Node(self, self.boarderWidth, sqrt(self.gridArea), x, y)
self.grids.append(square)``` this was my lazy method of making the grids
Ah, yes, i see.
from tkinter import *
root = Tk()
c=Canvas(root)
c.pack(side=TOP, fill=BOTH, expand=True)
root.update()
gap=20
cw=c.winfo_width()
ch=c.winfo_height()
for i in range(0, cw, gap):
c.create_line(i, 0, i, ch, fill="black")
for j in range(0, ch, 20):
c.create_line(0, j, cw, j, fill="black")
root.mainloop()
@abstract crown
Renders a grid of cells 20 pixels wide.
this created a nice looking grid but the canvases were unique and allowed me to interact with them directly.
You can always interact with any object on the canvas using tags.
See how my flood fill visualizer fills a section of the canvas using this grid technique.
Pretty fast, and optimised.
you should be a tkinter helper :D
Thanks :D
Would you mind to check my problem in #☕help-coffee
?
I have button that adds Entries , I want to store the input of the entries in a list
To get the text written in an Entry widget
text = entry.get()
myList.append(text)
@ivory abyss
im sorry i must be really annoying but my mind is so confused. How do i interact with the grid? do i get the mouse pos then draw a color?
See this @abstract crown :
def onclickDraw(event):
cell=[event.x//gap, event.y//gap]
canvas.create_rectangle(cell[0]*gap, cell[1]*gap, (cell[0]+1)*gap, (cell[1]+1)*gap, fill="cyan")
canvas.bind("<B1-Motion>", onclickDraw)
So that when you drag the mouse by pressing the left key, it draws rectangles over it.
oh wow
Just replace gap by 20
i sortof understand how this works
Very well.
thanks
whats wrong with this ```py
import tkinter as tk
HEIGHT = 700
WIDTH = 800
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tk.Frame(root, bg='black')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8
button = tk.Button(root, text="test Button", bg='grey', fg='red')
button.pack()
root.mainloop()
this was my error
` File "C:\Users\levil\OneDrive\Desktop\WeatherApp.py", line 14
button = tk.Button(root, text="test Button", bg='grey', fg='red')
^
SyntaxError: invalid syntax
Process finished with exit code 1`
help anyone?
you missing a bracket buddy
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
import tkinter as tk
root = tk.Tk()
root.title("Work Time")
root.geometry("600x400")
timer1 = tk.IntVar(root)
timer1_enabled = tk.IntVar(root)
name_var = tk.StringVar()
name_var_entry = tk.Entry(root, textvariable = name_var, font=('Ariel Rounded MT bold',10, 'bold'))
name_label = tk.Label(root, text = 'Total work time since start', font=('Ariel Rounded MT bold',10, 'bold'))
timer_entry = tk.Label(root,textvariable = timer1, font=('Ariel Rounded MT bold',10,'normal'))
start_btn=tk.Button(root,text = 'Start/Pause', command = timer1_enabled)
reset_btn=tk.Button(root,text = 'Reset', command = timer1_enabled)
name_var_entry.grid(row=1,sticky="W", column=1,pady=(110, 0), padx=(50, 0))
name_label.grid(row=2, sticky="W", column=1, pady=(10, 0), padx=(35, 0))
timer_entry.grid(row=3, sticky="W", column=1, pady=(5, 0), padx=(115, 0))
start_btn.grid(row=4, sticky="W", column=1, pady=(5, 0), padx=(45, 0))
reset_btn.grid(row=4, sticky="W", column=1, pady=(5, 0), padx=(145, 0))
def advance_timers():
if timer1_enabled.get():
timer1.set(timer1.get() + 1)
root.after(1000, advance_timers)
root.after(0, advance_timers)
root.mainloop()``` how did i make my buttons command work again? also i am aware that the reset and start/pause button have the same command but if i manage to make 1 work i expect to understand how to make it possible to pause and also reset then
Can anyone explain this part to me in PyQt5?
vline.addLayout(hline2)
window.setLayout(vline)```
@river compass sorry for the late reply, but there is practically no need for an IntVar instance. you can instead do this:
import tkinter as tk
root = tk.Tk()
root.title("Work Time")
root.geometry("600x400")
timer = 0
stop = False
name_var = tk.StringVar()
name_var_entry = tk.Entry(root, textvariable = name_var, font=('Ariel Rounded MT bold',10, 'bold'))
name_label = tk.Label(root, text = 'Total work time since start', font=('Ariel Rounded MT bold',10, 'bold'))
timer_entry = tk.Label(root,text = timer, font=('Ariel Rounded MT bold',10,'normal'))
def advance_timers():
global timer, stop
if stop == True:
stop = False
return
if stop == False:
timer += 1
timer_entry.config(text = timer)
root.after(999, advance_timers)
def pause():
global stop
stop = True
#advance_timers()
def reset_timer():
global timer, stop
stop = True
timer = 0
timer_entry.config(text = timer)
start_btn=tk.Button(root,text = 'Start', command = advance_timers)
pause_btn=tk.Button(root,text = 'Pause', command = pause)
reset_btn=tk.Button(root,text = 'Reset', command = reset_timer)
name_var_entry.grid(row=1,sticky="W", column=1,pady=(110, 0), padx=(50, 0))
name_label.grid(row=2, sticky="W", column=1, pady=(10, 0), padx=(35, 0))
timer_entry.grid(row=3, sticky="W", column=1, pady=(5, 0), padx=(115, 0))
start_btn.grid(row=4, sticky="W", column=1, pady=(5, 0), padx=(45, 0))
pause_btn.grid(row=5, sticky="W", column=1, pady=(5, 0), padx=(45, 0))
reset_btn.grid(row=4, sticky="W", column=1, pady=(5, 0), padx=(145, 0))
root.mainloop()
ty for the reply even if its late :D this helps a ton (and its easier to understand for me which makes me learn more :D)
no problem 😄
just to let you know, we called after() for 999 miliseconds, to cover up any delays.
ahhh
feel free to ask anything you dont understand in the code.
i think i still understand this like i can read it and see why it works
i can't recreate it but do understand it which is half way there
it can break pretty easily tho but thats fine
how do i make the white outline blue?
borderwidth=0, highlightthickness=0
where do i write this
where you put stuff in the tk.Canvas( line
Could someone tell me if there is any option to use "-type" attribute in tkinter
https://tcl.tk/man/tcl8.6/TkCmd/wm.htm#M19
because when I do
root.attributes("-type", "splash")
it throws me an error about wrong arguments
NOTE: I'm using windows
Hi, I write here but I don't know if this is the right channel. I'm working on a software that download images from the web and automatically save them. I'd like to download the images and show them before to save them, I've tried to use 'Image.open()' with PIL module but it doesn't work, I believe it only open files already existing. Sorry for my bad english.
@jade mist Since you havent posted any code my only guess is that you forgot to add show after. Image.open("some image").show()
Yes, sure. I've used .show() also but the Image.open() doesn't open any image since I've not saved it. The image I want to show is the response content of a request i made to a website
I'll post my code if necessary
@jade mist do it, without it we gonna play unnecessary game of guessing
import requests as req
from PIL import Image
url=input("website: ")# for example https://discord.com
res=req.get(url).content
img=Image.open(res)
img.show()```
@jade mist open takes path to an image file
so you need to save it first
Yo anbody here knows how to put images as FOREGROUND in tkinter?
Yeah, that's the problem I was talking about. I'd like to now if there's a way to show the downloaded image before to save it.
I resolved!
Using BytesIO:```py
from io import BytesIO
import requests
from PIL import Image
url=input('website: ')
r = requests.get(url)
img=BytesIO(r.content)
im = Image.open(img)
im.show()
@barren thorn on windows, no such attribute exists. The docs say it is a linux attribute.
But i am assuming you want to disable window borders?
root.overrideredirect(1)
Is what you're looking for, then.
@barren thorn
@digital rose nope, it also kills the tray. Sadly I will need to do it other way.
what do you mean kill the tray? overrideredirect() disables window borders.
@barren thorn
it also kills it on the tray
if youre talking of removing status from the taskbar, it will do it.
you can always make it show in the taskbar!
from tkinter import *
mainWindow = Tk()
mainWindow.geometry("500x500+400+40")
mainWindow.overrideredirect(1)
status = Toplevel(mainWindow) # to make 'tk' show in taskbar.
status.wm_attributes('-alpha', 0.0) # hides the toplevel.
def killAll(event):
status.destroy()
mainWindow.destroy()
mainWindow.bind("<Escape>", killAll)
mainWindow.mainloop()
status.mainloop()
@barren thorn this approach seems to work just fine. you can see a reference to 'tk', otherwise a tkinter window in the taskbar.
yes, but this just seem like a hack, my guess is that I will use the windows api to do this
@digital rose
class LoginPage:
def __init__(self, root):
self.root = root
self.root.geometry("1450x700+0+0")
self.root.title("Login Page")
self.title_label = Label(self.root, text="system", font=("Arial", 35, "bold"),
bg="lightpink", bd=8, relief=GROOVE)
self.title_label.pack(side=TOP, fill=X)
self.main_frame = Frame(self.root, bg="aliceblue", bd=6, relief=GROOVE)
self.main_frame.place(x=280, y=150, width=900, height=400)
self.login_lbl = Label(self.main_frame, text="Login Page ", font=("Arial", 20, "bold"), bd=6, bg="aliceblue",anchor=CENTER)
self.login_lbl.pack(side=TOP, fill=X)
self.email = Label(self.main_frame, text="Email-id", font=("Arial", 20, "bold"))
self.email.grid(row=0, column=0)
error:-
C:\Users\GoLu\AppData\Local\Programs\Python\Python39\python.exe E:/document/python/project/test.py
Traceback (most recent call last):
File "E:\document\python\project\test.py", line 62, in <module>
main()
File "E:\document\python\project\test.py", line 36, in main
app = LoginPage(root)
File "E:\document\python\project\test.py", line 58, in __init__
self.email.grid(row=0, column=0)
File "C:\Users\GoLu\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2485, in grid_configure
self.tk.call(
_tkinter.TclError: cannot use geometry manager grid inside .!frame which already has slaves managed by pack
how can I fix this?
@neon steppe you can use only grid or only pack
very well. you are free to use it, just to let you know it isnt a hack.
I have used grid in last label
🤔 so can I use grid in both frame and label
you need to show the code, so that i can help you out.
from tkinter import *
def main():
root = Tk()
app = LoginPage(root)
root.mainloop()
class LoginPage:
def __init__(self, root):
self.root = root
self.root.geometry("1450x700+0+0")
self.root.title("Login Page")
self.title_label = Label(self.root, text="Resturant managment System", font=("Arial", 35, "bold"),bg="lightpink", bd=8, relief=GROOVE)
self.title_label.pack(side=TOP, fill=X)
self.main_frame = Frame(self.root, bg="aliceblue", bd=6, relief=GROOVE)
self.main_frame.place(x=280, y=150, width=900, height=400)
self.login_lbl = Label(self.main_frame, text="Login Page ", font=("Arial", 20, "bold"), bd=6, bg="aliceblue",anchor=CENTER)
self.login_lbl.pack(side=TOP, fill=X)
self.email = Label(self.main_frame, text="Email-id", font=("Arial", 20, "bold"))
self.email.grid(row=0, column=0)
if __name__ == '__main__':
main()
my whole code
@digital rose
@neon steppe change:
self.email.grid(row=0, column=0)
to:
self.email.pack(side=TOP, anchor=NW)
thankx
😁
🤔 I have a question, Why I cannot use grid ?
a frame is a container. tkinter expects you to have some uniformity when rendering widgets inside of a frame, so you can use either - .grid() or .pack().
but only one throughout.
ok ok
whats wrong with this code
import tkinter as tk
HEIGHT = 700
WIDTH = 800
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH, bg='black', borderwidth=0, highlightthickness=0)
canvas.pack()
frame = tk.Frame(root, bg='white')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.5)
button = tk.Button(frame, text="test Button", bg='#ff02e6', fg='cyan')
button.grid(relx=0, rely=0, relwidth=0.25, relheight=0.25)
label = tk.Label(frame, text='this is a label', bg='cyan', fg='#ff02e6')
label.grid(relx=0.3, rely=0, relwidth=0.45, relhight=0.25)
entry = tk.Entry(frame, bg='purple')
entry.grid(relx=0.8, rely=0, relwidth=0.2, relheight=0.25)
root.mainloop()
?
What's the error?
@open lintel change all .grid() to .place(), but dont change the options inside. Also you've spelt height wrong in label.grid().
relx, rely, relwidth and relheight are args for .place().
Guys what GUI would you recommend to making a pretty user interface? I read that Tkinter is good but I saw the examples of people doing interfaces and they aren't really great.. also I saw some examples of PyQT5 and I saw that the examples are better, more modern, is that something to do with the GUI itself or you can achieve same results by using any of them?
Depends on what your experience with GUIs is. If you're a complete newbie, Tkinter is the best choice. PyQT is good, with nice stylesheets, but its possible to replicate almost all pretty UI layouts in tkinter, because its quite flexible. Still, it all depends on your experience with,writing GUIs. Im not going to lie to you. Writing UIs sometimes needs custom stuff, like custom button layouts, etc, and in those cases native Libraries will not suffice.
@split meadow
Loved this answer!!! Thank you so much for taking the time to reply to it !! I appreciate it a lot !!
🍪 Here's a cookie for you
@digital rose
Thank you so much :D
Something to keep in mind is - You can mix grid and place and also place and pack
And in any case, how is it sensible to keep on interchanging geometry methods?
I have seen people use. Just mentioning that it wont throw an error at you
Very well. A thing to keep in mind is to not go with what others do, but what is sensible code practice.
Fair enough
foreground of what?
Any idea why pack() and place() does not show one of them, inside a frame?
What do you mean?
You did mention something about rendering.
from tkinter import *
root = Tk()
f = Frame(root,bg='red')
f.pack()
Label(f,text='PYSCH~').pack()
Label(f,text='adasd').place(x=20,y=100)
root.mainloop()
You can see the 2nd label not appearing
@digital rose
You're just rendering the 2nd label beyond the dimensions of the frame, which fits the size of the first label. Try:
# for the second label
Label(f,text="adasd").place(x=0,y=20)
``` see how the second label appears. @tawdry mulch
At the same time it's strange to see a thing like that happen, when the first widget rendered into the frame, the frame fits to its size.
No luck in that
I see overlapped labels.
Hmmm pixels vary.
You didnt say anything about proper rendering
x=0,y=10 does that for me
Fair enough. Thanks for taking a dig.
Good day.
Well if anyone in future would want to know, you can use f.pack_propagte(0) to make it force listen to the required dimensions. Like height=100,width=100.
A code that works would be something similar to:
from tkinter import *
root = Tk()
f = Frame(root,height=100,width=100)
f.pack()
f.pack_propagate(0)
Label(f,text='PYSCH~').pack()
Label(f,text='adasd').place(x=0,y=20)
root.mainloop()
Buttons, Labels and all has image option to it. But an entire window does not
Button(root,image=img)
Wont that make the button have the image as like the texture?
Okay I just found out that tkinter doesnt support transparent images
so nevermind
Hmmhmm
It does
Canvas.create_image() supports RGBA images.
Oh ;-; but you cant put entry widgets on a canvas
All I want is a custom theme using images
Thats why im asking for help on how to import images with transparent background
Canvas.create_window(x1,y1,window=entry)
How exactly? Do you have any example that I could see?
Okay so i tried and it only shows the widget ;-;
and my image still doest overlap the entry box
Should'nt you also be saying canvas = Canvas(...) first.
I just gave an example using Canvas.create_image(). You should use a variable name, not the class itself.
hey guys! i recently learned OOP and i am learning more of Python. I wanted to ask that which standard libraries should i learn to create a GUI like KivyMD since i plan to make a GUI from scratch
hey guys, I am making a tkinter matrix multiplication code which takes 2 matrices as input through GUI. I made the first window which looks like this:
here's the code for the window:
matrix1 = Tk()
matrix1.title("matrix 1")
matrix1.resizable(False, False)
for i in range(total_rows1):
for j in range(total_columns1):
globals()["e1"+str(i+1)+str(j+1)] = Entry(matrix1, width=5, fg='blue', font=('Arial',16,'bold'))
globals()["e1"+str(i+1)+str(j+1)].grid(row=i, column=j)
Button(text="Enter", padx=10, pady=5, command = AskForMatrix2).grid(row = 2, column = total_columns1+2)
matrix1.mainloop()
all I am doing is I am arranging the entries in a grid as per the rows and columns previously input by the user
I am also getting the "Enter" button which works fine
but
after pressing 'enter', the code is supposed to ask for the second matrix, which works for me, all I did was make a Toplevel() window when the button is pressed
here is the second window
here's the code for the second window
matrix2 = Toplevel()
matrix2.title("matrix 2")
matrix2.resizable(False, False)
for i in range(total_rows2):
for j in range(total_columns2):
globals()["e2"+str(i+1)+str(j+1)] = Entry(matrix2, width=5, fg='blue', font=('Arial',16,'bold'))
globals()["e2"+str(i+1)+str(j+1)].grid(row=i, column=j)
Button(text="Enter", padx=10, pady=5, command = EnterMatrix2).grid(row = 2, column = total_columns2+2)
as you can see, its almost similar to the matrix1 window, but the problem is that the 'enter' button is not appearing for the second window
I tried searching on google, but did not get a good answer...
Hey @rigid niche!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
hey uuuh how do I use canvas on a 2nd window in tkinter, It gives an error "Canvas is not callable"
That is not the best way to use globals()
oww
Can you give a runnable code
its there in the link
Try: Button(matrix2,text="Enter", padx=10, pady=5, command = EnterMatrix2).grid(row = 2, column = total_columns2+2)
Added matrix2 at the first @rigid niche
Why not KivyMD itself?
Can you show us the code
Nop I used label instead
but now
it doesnt show up
Even though I used label
def Show_Calculator():
global Fresh_Calculator
screen2 = Toplevel()
screen2.title("Calculator")
screen2.iconbitmap("Hands On Activity 3.1/Maksci Icon.ico")
screen2.geometry("400x600")
screen2.resizable(0,0)
Fresh_Calculator = Image.open("Hands On Activity 3.2/Assets/Calculator Set Up.PNG")
Transform_Calculator = Fresh_Calculator.resize((10,600), Image.ANTIALIAS)
Calculator = ImageTk.PhotoImage(Transform_Calculator)
Label_Calculator = Label(screen2, image=Calculator)
Label_Calculator.place(x=0,y=0)
Number_1 = Button(screen2, text="1", fg = 'white', bg = 'green', activebackground = '#1BC621')
Number_1.place(x=10, y=567, width=50, height=50)
As you can see
its just like a normal window
say root.image = calculator
This is the channel for user-interfaces only.
Okay then say screen.image = calculator before the function ends
Oh wow that actually works
why do i need to type that though?
what does it do???
When a function ends, every variable that are not reused outside of the function is removed by the garbage collector of Python. But you need this image to be shown, so you have to keep a reference to the image. One way is saying global calculator or screen.whatevernameyouwant = calculator
i can use it but i would love to make a GUI library from scratch
You want to make a GUI or a library that makes GUI?
a library that makes GUI
Well it wont be easy. You have to understand how the windows are managed by each OS. And the concepts of event loops. In windows its win32 event message loop (https://docs.microsoft.com/en-us/windows/win32/learnwin32/window-messages)
There are libraries to make the jobs easier, why make one(now). Especially people use python just to get hands on these libraries.
okay, will keep this in mind
yo how do i italiciz my text in a button?
Does using italian text directly not work?
Italicize like this
What framework are you using?
tkinter
Show the code, just change the font option to italics.
Button(root,text='Hello World',font=(0,0,'italic') should work
I am making a basic app using Tkniter but i am stuck with the following, I'm looking update my canvas each time a button is clicked as the image will change (The image within the file changes, just doesnt update with tkniter). Any help would be great Just @ me
Im trying to make use of a hand tracking software that allows me to make bounding boxes that allow for squares and rectangles to be used, for example a fist would be a square and an open hand would be a rectangle. I'm using Mediapipe currently as they have bounding boxes that can be used as it uses CV2, however they don't change shape dependent on hand position. I've been able to draw rectangles or squares onto the image just using code like this :
[14:38]
for rect in results.hand_rects:
pt1 = (int(rect.x_center * size[1] - ((rect.width * size[1]) / 3)), int(rect.y_center * size[0] - ((rect.height * size[0]) / 3)))
pt2 = (int(rect.x_center * size[1] + ((rect.width * size[1]) / 3)), int(rect.y_center * size[0] + ((rect.height * size[0]) / 3)))
[14:39]
but it only allows for one shape to be made, has anyone got any suggestions or anything?
nop its good dont worry i needed a tuple lol
Sure, post your code we will take a look here
Is this GUI based question? I really dont think so, why dont you ask this in one of the help channels
Where else should I put it? I've tried the help channels a few times however my question doesn't get answered
Hmmmm it means the people dont actually get it, if this is a mistake or an error. You could ask this @ stackoverflow
Okay cool thankyou I'll put it on there
Sweet, This is my code for the canvas & image
url = "http:" + dict["icon"] # This image is dependent on what the API call provides
r = requests.get(url, allow_redirects=True)
open('WeatherImage.png', 'wb').write(r.content) # Will overwrite the current image with a new one when the button is clicked
image_holder = Canvas(root, bg='Grey', width=80, height=80)
image_holder.place(x=15, y=15)
myimg = PhotoImage(file='WeatherImage.png')
image_holder.create_image(40,40, image=myimg)
Just to make sure, the image is all fine right? When you open it separate @brittle bolt
So the issue i'm having, is when i click the button it will display myimg but lets say myimg = a square, the app will display the sqaure, but when i click the button the API might change it to a circle. So what happens is myimg = circle but Tkniter hasnt refreshed myimg so it still producing a square - If that makes sense & thats what your asking 😄
How do you know the API has changed the image? are there any intervals?
so when the button is clicked it will produce a URL which is used to display an image based of the weather (its a weather app im making)
so the intervals are based on when the user clicks the button
So url = "http:" + dict["icon"] would change right? @brittle bolt
yea
Okay cool, fairly easy.
Create a function and link it to a button
inside the function do the same exact thing
Okay
But first you need to be able to "update" the image right
So change image_holder.create_image(40,40, image=myimg) to image_holder.create_image(40,40, image=myimg,tag='image')
First create a function and then I'll guide you from there.
Or if you want me to code, just lemme know @brittle bolt
Either or, i'm happy to follow along
I just need 2 mins to do something irl then ill be back
Okay cool, try coding on your own, ill help with any mistakes
Ok, so the canvas goes blank
with the button
So, how do i update the image to tkniter?
Eh, no clue tbh :D, i'll give it a look
Okay
wym?
def ClearScreen():
output1.config(text="")
output2.config(text="")
output3.config(text="")
output4.config(text="")
url = "http:" + dict["icon"]
r = requests.get(url, allow_redirects=True)
open('WeatherImage.png', 'wb').write(r.content)
image_holder = Canvas(root, bg='Grey', width=80, height=80)
image_holder.place(x=15, y=15)
myimg = PhotoImage(file='WeatherImage.png')
image_holder.create_image(40,40, image=myimg, tag="image")
you were referring to image above right?
oh thats just a bunch of labels, that when the button is clicked replaces any text to a empty string. as i didnt know how to refresh it 😄
def ClearScreen():
output1.config(text="")
output2.config(text="")
output3.config(text="")
output4.config(text="")
url = "http:" + dict["icon"]
r = requests.get(url, allow_redirects=True)
open('WeatherImage.png', 'wb').write(r.content)
myimg = PhotoImage(file='WeatherImage.png')
image_holder.itemconfig("image",image=myimg)
Try this
It didnt work : (
Explain? What happened
I can upload the full code, i'll just need to do it via codepen or somthing
Image stayed the same
Nothing happened to the canvas
Did you associate the command to a button? 😉
I mean command=ClearScreen for button
yea i did hah
Post the entire code, let me see
Ok, 1 seco
No errors even?
I am not sure, there is service here
try pasting entire code here, i think they vl give a link to their paste service
Hey @brittle bolt!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Had to use that, File was to big, Bot thought was spam
I forgot something though, try to say global myimg.
Bro you did not give tag at line 151
image_holder.create_image(40,40, image=myimg, tag='image')
It doesn't work still - i did try but forgot to add it back : (
Can you update the code
yea
Wait
Think it is (may of put global in wrong spot by mistake)
okay it is working ty
inside ClearScreen
But slight issue on my end, is it possible to have it do this when the main button is clicked?
Which is main button
I got it, thank you very much
I just moved it to a new function within the main function 😄 it works
Okay sure 😄
Man, i have been stuck on this for like a solid a week and when i googled it the examples were confusing & so far off each any other examples that i couldnt tell what to follow
Its always something simple 😉
haha, Thank you again man
Anytime 😄
this better?
HEIGHT = 700
WIDTH = 800
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH, bg='black', borderwidth=0, highlightthickness=0)
canvas.pack()
frame = tk.Frame(root, bg='white')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.5)
button = tk.Button(frame, text="test Button", bg='#ff02e6', fg='cyan')
button.place(relx=0, rely=0, relwidth=0.25, relheight=0.25)
label = tk.Label(frame, text='this is a label', bg='cyan', fg='#ff02e6')
label.place(relx=0.3, rely=0, relwidth=0.45, relheight=0.25)
entry = tk.Entry(frame, bg='purple')
entry.place(relx=0.8, rely=0, relwidth=0.2, relheight=0.25)
root.mainloop()
is this better anyone>
Yes.
Hello, does someone know how to use Pyinstaller when you have a Python script that calls subscripts and files?. I launched it the regular way, but the .EXE does nothing when i click on. It works only through the Terminal and only if allocated in the same folder of the subscripts. I suspect i have to modify something in the .spec?
whats wrong with this code
import tkinter as tk
HEIGHT = 700
WIDTH = 800
def test_function():
print("Button Clicked!")
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH, borderwidth=0, highlightthickness=0)
canvas.pack()
background_image = tk.PhotoImage(file='download.png')
background_label = tk.Label(root, image=background_image)
background.label.place(relwidth=1, relheight=1)
frame = tk.Frame(root, bg='#80c1ff', bd=5)
frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')
entry = tk.Entry(frame, font=40)
entry.place(relwidth=0.65, relheight=1)
button = tk.Button(frame, text="Get weather!", bg='gray', command=test_function)
button.place(relx=0.7, relheight=1, relwidth=0.3)
lower_frame = tk.Frame(root, bg="#80c1ff", bd=10)
lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')
label = tk.Label(lower_frame)
label.place(relwidth=1, relheight=1)
root.mainloop()
You might want to say the issue your having to help someone narrow it down
Which libraries do you use.
Nothing is wrong here
Hi is someone here experienced with making ui using pyqt5? i need help on that and will prolly require help later too so anyone willing to help?
My Help channel got marked as dormant for the second time 😦 Could someone just quickly help me here? It's a quick issue
How do I make def leave close the root window?
I think I need to pass the variables through but I forgot how
class Application(tk.Tk):
def topbar(self):
def leave():
try:
self.destroy()
except:
pass
def softwareversion():
def close():
root.destroy()
root = Tk()
root.title("Software Version")
label2 = ttk.Label(root, text="You are running xyz version 1.8.9 BETA", font=Information_Font,) #background="red")
label2.pack(pady=0,padx=50)
no = tk.Button(root, text = "Close", width = "8", command = close)
no.pack(pady=4,padx=50)
self.menuBar = Menu(master=self)
self.filemenu = Menu(self.menuBar, tearoff=0)
self.infomenu = Menu(self.menuBar, tearoff=0)
self.helpmenu = Menu(self.menuBar, tearoff=0)
self.viewmenu = Menu(self.menuBar, tearoff=0)
self.filemenu.add_command(label="Hello!")
self.filemenu.add_command(label="Exit!", command=leave )
self.infomenu.add_command(label="Software Version", command=softwareversion)
self.infomenu.add_command(label="Switch CLI Version")
self.helpmenu.add_command(label="About")
self.menuBar.add_cascade(label="File", menu=self.filemenu)
self.menuBar.add_cascade(label="Help", menu=self.helpmenu)
self.menuBar.add_cascade(label="Info", menu=self.infomenu)
self.menuBar.add_cascade(label="View", menu=self.viewmenu)
ask away
alright
but how do i design the buttons and text fields like that, and make the text look better with the icon tho?
also do you mind if i dm you regarding this later?
just ask here
alr
i will not be online all the time
np
ah you cannot resize
use QtCreator instead
or create a smaller window which is resizable
oh ok
I have 4 labels, & each time the button is clicked the text is going to change so how can i clear the current text when the button is clicked?, I have tried to do things like output1.config(text="") aiming to set the label to a empty one, However is just get this:
Text is just over lapping each other
@brittle bolt you dont need to clear the text, you can just do this:
output1.config("new text")
and now, bind command to a button, for example:
def ChangeTextOnClick():
output1.config(text = "new text")
button1 = Button(window, text = "Click Me!", command = ChangeTextOnClick)
button1.pack(side=TOP)
something like this.
i tried this
mm hmm, you will need to show some more code for reference.
So right now, i have this: - This is in a button, but text just over laps
output1 = Label(root,)
output1.config(bg = 'white', font=("Times", 18), text=dict["name"]) # dict["name"] This changes eah time. Example, New York, London, Japan, etc
output1.place(x=475, y=30)
I did have a way using two separate buttons but would much rather have it just work under one button
right. from what i see is you need to create a button, and add a command to the button to change the text every time. for example:
# this is the command to change the text every time.
def onClick():
output1.config(text = dict['name'])
button = Button( .. .. .. , command = onClick)
button.place( .. . )
@brittle bolt
mm hmm. what text do you presently have on your label?
overlap?
!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.
To start with the labels are blanked, untill the user requests the data from the API which will then populate them
ah.
it seems like you have created two labels, one saying something like "homework" and the other one saying something like "new york"?
yea, one is the region of the location & one is name of it
but when u search for another location, the text just pastes it self on top
dosent remove the previous text
ah. i see the problem now. you dont need two labels for that. just do this:
location = "something"
output1.config(text = f"Location -> {location}")
in other words, using string formatting to join two things together.
so now, you just keep on updating the variable location and config the text like that^.
tkinter will automatically use the updated value of location to change the text.
Right, so mine would like
location = dict["name"]
output1.config(text = f"Location -> {location}")
?
yes, something like this.
in other words, using string formatting to join two things together.
So its going to join the two words together
yes.
its only going to update the variable part, you dont need a second label for that.
I'm trying to avoid that, the two labels are meant to be separate. One is region & the other is Name, What i'm aiming to do when the Button is clicked to update the text in region & Name
Inside my button i have this, but it doesnt update the text, instead just will put the new text on top of the old text (causing overlap)
output1 = Label(root,)
output1.config(bg = 'white', font=("Times", 18), text=dict["name"])
output1.place(x=475, y=30
right. i think you can do something like this:
# name the labels something better to understand it better:
name = "Los Angeles"
region = "something"
name_label = Label(root, text = f"Place: {name}"
name_label.place( .. .)
region_label = Label(root, text = f"Region: {regiom}"
region_label.place( .. .)
create two separate labels, one for Name and the other for region.
Okay, will do, 1 min and i will try it
Name_Text = dict["name"]
Name = Label(root,)
Name.config(bg = 'white', font=("Times", 18), text=f"{Name_Text}")
Name.place(x=475, y=30)
Region_Text = dict["region"]
Region = Label(root,)
Region.config(bg = 'white', font=("Times", 17), text=f"{Region_Text}")
Region.place(x=475, y=65)
I have this, is this correct?
yes it does seem correct. and another thing, you dont need to do this:
something = Label(root,)
something.config( .. )
you can do this:
something = Label(root, text = "", font = .. )
something.place( .. . )
Okay & i still have the same issue : (
Text is just overlapping
can you send a screenshot?
Yea
and the updated code as well.
where do you see an overlap?
you're talking about the labels overlapping with the F or C button?
i see what you did wrong there.
you render a new label everytime in API().
that is why it overlaps.
Ah, so remove the label() out of the function but leave the config() in?
instead do this:
def API():
global Name, Region # to prevent errors.
# leave the rest of the code unchanged.
# just change label text.
Name.config(text = Name_Text) # because Name_Text gets updated everytime you search.
Region.config(text = Region_Text)
# now here, leave the rest unchanged, but draw the labels here,
Name = Label( .. . )
Region = Label( .. .. )
yes, precisely.
what you did wrong was to create a new label every time you searched for a new location, so they kept on piling up.
Ah, Thank you for the help, i'll make them changes now
here, i did the work for you @brittle bolt .
https://paste.pythondiscord.com/tolekadapa.py
@digital rose Thank you for the help, Works perfect
no problem 😄
Does apps made with Qtdesigner actually use coordinates? If I run the app in another system with different resolution will it change its position from what was given in the designer? @modern marsh
File "frontend.py", line 24, in <module>
PyDFApp().run()
File "C:\Users\JERSON\AppData\Local\Programs\Python\Python38\lib\site-packages\kivy\app.py", line 949, in run
self._run_prepare()
File "C:\Users\JERSON\AppData\Local\Programs\Python\Python38\lib\site-packages\kivy\app.py", line 919, in _run_prepare
root = self.build()
File "frontend.py", line 20, in build
return TextEditor()
File "frontend.py", line 13, in __init__
self.add_widget(NavBar())
File "C:\Users\JERSON\AppData\Local\Programs\Python\Python38\lib\site-packages\kivy\uix\widget.py", line 622, in add_widget
widget.inc_disabled(self._disabled_count)
AttributeError: 'TextEditor' object has no attribute '_disabled_count'```im getting this traceback
i dunno what that error means
this is my code btw
class NavBar(Widget):
pass
class TextEditor(Widget):
def __init__(self):
self.add_widget(NavBar())
self.text_editor = TextInput(font_size=30, center_x=50, top=root.top-40, size=(root.width,1000), background_color=(0.1, 0.1, 0.1, 1))
self.add_widget(self.text_editor)
class PyDFApp(App):
def build(self):
return TextEditor()```
yes im using kivy
if i develop an app using pyqt5 designer and python with the right mobile res, will it be able to run on android?
Uhh I don't think PyQt5 can be used for mobile dev
Ig only QtQuick is available for mobile dev
Hmm ig I'm wrong
My source is a 2013 SO post
Lemme check the current compatibility
Will the apps be the same size in all resolutions @modern marsh
in what exactly?
Apps made with Qt designer
for PC?
Yea PC with different resolution
uh
well suppose you make a 640x480 app in a 1080p screen
when you run it on 4k it will be too small
If I make the app in 1920x1080 and then try the app in a 640 will it look same?
you might have to adjust the sizes per res
what do you mean by same
content wise yes
relative size to screen , no
well
check resolution and scale accordingly was what i did in tkinter
in Qt idk
better to google it
Hmmm how did you do scaling in tkinter, ive been trying for a while now 😅
by scaling i dont mean scaling individual widgets
just scaling the window
to check resolution
there is a WM_height or something attribute
Viseur will know better
I am aware of that method but
there is a resizeEvent in Qt
