from PIL import ImageTk,Image
import threading
root = Tk()
width = 1280
height = 720
root.geometry(f"{width}x{height}")
root.title("WK Industries for Web Development and software developement")
global frames , count, frameCnt
count = -1
# Image List for Gif
imageObject = Image.open("./giphy.gif")
frameCnt = imageObject.n_frames # This will get the number of frames in a gif
frames = [PhotoImage(file='./giphy.gif',format = 'gif -index %i' %(i)) for i in range(frameCnt)] # This will extract the frames as
#Create Canvas to hold image
background_canvas = Canvas(root, width=1280,height=720,highlightthickness=0)
#background_canvas.grid(columnspan=3, rowspan=2, row=0)
background_canvas.pack(fill='both',expand=True,side='top')
#set Image to canvas
background_canvas.create_image(0,0,image=frames[0],anchor="nw")
# Next()
def next():
global count, frameCnt
if count == frameCnt-1:
background_canvas.create_image(0,0,image=frames[0],anchor="nw")
count = 0
else:
background_canvas.create_image(0,0,image=frames[count + 1],anchor="nw")
count += 1
print(count)
root.after(100,next)
# OR next()
threading.Thread(target=next).start()
mainloop()```
#user-interfaces
1 messages Β· Page 84 of 1
is it absolutely necessary to uses classes to make pyqt5 GUI??
Can I somehow do it without classes??
Yes
But your code will be very messy and very hard to maintain
And because of that it'll be more prone to bugs.
What makes you avoid classes anyway? They're very useful in python.
Hey, I'm developing a shell and I'm using prompt-toolkit for creating the final prompt. There is a class called HTML that converts a html-like string into usable prompt but it doesn't accept transparent as a valid color, if i dont specify any foreground, output looks like this.
Does anyone know, how to make it transparent ?
I'm trying to paste an image whenever "incorrect_count" equals a specific number. It pastes the first image, but it doesn't add any more images.
incorrect_count += 1
if incorrect_count >= 6:
progress_label.config(text="Oops! Game over!")
img = ImageTk.PhotoImage(Image.open('Images/right_leg.png'))
panel = tkinter.Label(wn, image=img)
panel.image = img
panel.pack(side="bottom", fill="both", expand="yes")
game_over = True
if incorrect_count == 1:
img = ImageTk.PhotoImage(Image.open('Images/head.png'))
panel = tkinter.Label(wn, image=img)
panel.image = img
panel.pack(side="bottom", fill="both", expand="yes")
if incorrect_count == 2:
img = ImageTk.PhotoImage(Image.open('Images/torso.png'))
panel = tkinter.Label(wn, image=img)
panel.image = img
panel.pack(side="bottom", fill="both", expand="yes")
if incorrect_count == 3:
img = ImageTk.PhotoImage(Image.open('Images/left_arm.png'))
panel = tkinter.Label(wn, image=img)
panel.image = img
panel.pack(side="bottom", fill="both", expand="yes")
if incorrect_count == 4:
img = ImageTk.PhotoImage(Image.open('Images/right_arm.png'))
panel = tkinter.Label(wn, image=img)
panel.image = img
panel.pack(side="bottom", fill="both", expand="yes")
if incorrect_count == 5:
img = ImageTk.PhotoImage(Image.open('Images/left_leg.png'))
panel = tkinter.Label(wn, image=img)
panel.image = img
panel.pack(side="bottom", fill="both", expand="yes")
god
A lot of this code can be deduplicated by just taking it out of the ifs.
try to add all those images to a single list and loop through them
I too feel that but im not allowed to use classes in this project im working on
Hello guys! I just wanna ask is there any ways to separate public user login and admin logins? Because I'm struggling with tkinter haha
os.system() function , you guys might need when making well organized tkinter app
Does Kivy work on M1 Macs? I always get an error when trying to run the example application
well made π
thank you π
:incoming_envelope: :ok_hand: applied mute to @digital rose until <t:1634219398:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
Using pyqt5 to make a gui within python, And I am making a long in screen. I also have a button that shows the register account instead. However I can't seem to get it to show the 2nd window.
Would anyone be willing to help please.
Any explanation why its displaying --01 instead -01 , as in termial also it display the count as -01
Any explanation why its displaying --01 instead -01 , as in termial also it display the count as -01
show the code
Aah its just simple
This one handles the display
to_strdigits is the function which takes int i out and converts it to string of given number, here 3
This function works fine as can be seen in terminal
it shouldnt happen like you are saying
maybe you are overwriting a variable at some point, idk
Cant say, might be some glitch
Sometimes things are correct but dont work , then after some here and there it tarts to work as i thought
############ IMPORTS ############
# Libraries
import tkinter as tk;
from tkinter import *
import tkinter.filedialog;
from PIL import *;
import glob;
#################################
class mainMenu:
def __init__(self) -> None:
return None;
def menuStart(self) -> None:
def backgroundDisplay():
bg = tk.PhotoImage(file = "../resources/MainMenuBG.png");
OpenImg = tk.Label(self.window, image = bg);
OpenImg.place(x = 0, y = 0, relwidth = 1, relheight = 1);
self.window = tk.Tk();
self.window.title("some gui")
self.window.iconbitmap(); #Icon for window
backgroundDisplay();
self.window.mainloop();
menu = mainMenu();
menu.menuStart();
The background image will not show and I'm not sure why (the path is correct)
Try self.bg = tk.PhotoImage(file="../resources/MainMenuBG.png")
yess it worked, ty!
def addApps():
for widget in frame.winfo_children():
widget.destroy()
filename1 = filedialog.askopenfilename(initialdir="/", title="Select File",
filetypes= (("executables", "*.exe"), ("All files", "*.*")))
filename1.split('/')[-1:][0]
apps.append(filename1)
print(f"{filename1}, {apps}")
for app in apps:
label = tk.Button(frame, text=app.split('/')[-1:][0], padx=0.5, pady=0.05, bg="#1c1c1c", fg='white', font=("Helvetica 12 bold"), command=infoWindow)
label.pack()
label['borderwidth'] = 0
return filename1
filename =
anyway to make filename = filename1?
incorrect_count += 1
img = ImageTk.PhotoImage(Image.open('Images/head.png'))
panel = tkinter.Label(wn, image=None)
panel.pack(side="bottom", fill="both", expand="yes")
if incorrect_count >= 6:
progress_label.config(text="Oops! Game over!")
img = ImageTk.PhotoImage(Image.open('Images/right_leg.png'))
panel.image = img
game_over = True
if incorrect_count == 1:
panel.image = img
if incorrect_count == 2:
img = ImageTk.PhotoImage(Image.open('Images/torso.png'))
panel.image = img
if incorrect_count == 3:
img = ImageTk.PhotoImage(Image.open('Images/left_arm.png'))
panel.image = img
if incorrect_count == 4:
img = ImageTk.PhotoImage(Image.open('Images/right_arm.png'))
panel.image = img
if incorrect_count == 5:
img = ImageTk.PhotoImage(Image.open('Images/left_leg.png'))
panel.image = img
``` I don't know why it isn't showing the image. Its updating the size but isn't actually showing the image.
guys i wanted to ask Kivy and QT are only packages for softwares made by python to be considered as products?
whats the difference b/w QT and PyQt? or are they just the same thing.
@heady brook
QT: A widget toolkit for creating graphical user interfaces written in C++
PyQt: A Python binding of Qt
Hi, im building a program with tkinter, is there anyway to make Frame object to follow mouse poision? (eg. like we do by draging )?
:incoming_envelope: :ok_hand: applied mute to @digital rose until <t:1634386394:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
I am making minesweeper (try 2 with proper classes and game modules) so i am arrived at the point where i provide play again feature so which thing is better overwrite the classes or update information contained in them
.
Start game fn
Making a new instance of a class is an easy way to reset it back to it initial values.
While working with classes i founf that its not easier sometimes
Weired results happen sometimes
Yes everything depends on the context its used in.
If the class was a GUI you might not want it creating a new GUI, but in another use case you do, so it all depends.
Imma try to manipulate somechanges to see it new instance with same variable works
Try img = PhotoImage(file=filepath)
I use this for image
Is there a way to animate short bits of movement without having to call place over and over? I want to draw a pop-up notification on the canvas with the diagram on it
Print incorrect_count to see if it where you want it to be
Which is better for GUI applications Kivy or PyQt?
How do you change a canvas size in tkinter once it's already set up? the config function is not working for me (boo https://stackoverflow.com/a/9589935/10241514)
I'm trying to convert an entire turtle graphics canvas including parts off scrollbars to a png with ghostscript ```py
import turtle, tkinter, subprocess
turtle.setup(800, 600)
turtle.screensize(3000, 1000)
for _ in range(4):
turtle.fd(100)
turtle.right(90)
canvas = turtle.getcanvas()
_canvas: tkinter.Canvas = canvas._canvas
_canvas.config(width=3000, height=1000)
_canvas.update() # seems to do nothing
print(_canvas.winfo_width(), _canvas.winfo_height()) # want 3000 1000, getting 779 579
_canvas.postscript(file='out.eps')
eps to png with ghostscript
subprocess.run('gswin64c -q -dSAFER -dBATCH -dNOPAUSE -dEPSCrop -r96 -sDEVICE=pngalpha -sOutputFile=out.png out.eps')```
The png conversion works fine but it's always 800x600 (or nearly due to border), not 3000x1000 like I want - _canvas.config(width=3000, height=1000) does nothing to the canvas 
Wait I think I got it
py canvas.postscript(file='out.eps', width=3000, height=1000, x=-1500, y=-500)
postscript itself has args
though it's 2999x1000 
Hello how to fix this error pls
Error: https://paste.pythondiscord.com/ehilorijas.sql
Tools:
Console: Windows Terminal
Editor: VScode
Python version: 3.8.10
this is personal project in local
My test code
it still isn't working :(
i tried it and incorrect_count is working
Close enuf
Working? Which if statement does it trigger and what is its value
In Tkinter I created a function that display a label & a photo , I linked this function with a button , when I execute the code the label is displayed but the photo is empty .
Any solution pleas ?```python
def prin():
if c.get() == pack1.name:
pic = tkinter.PhotoImage(file =r"C:\Users\pc\PycharmProjects\QuitSmoking\Marlboro.png")
l = Label(window,image=pic)
l.place(x=0, y=90)
label = Label(window,text=f"The price of a {pack1.name} pack is {pack1.price}DH\n it contains {pack1.nicotine} mg nicotines",bg='#efcb68',fg='#535F6B'
,borderwidth=2, relief="solid")
label.place(x=385,y=94)
label.configure(font=("Staatliches", 10, "bold") )
You need to keep a reference to the image add
l.pic = pic
After the label is created that is showing the image
ignore the fact that i dont have a function called clicked.
Tysm ππ½
why is my picture not coming up as a background it is just empty no error message?
Try text.schoolproj_image = img or root.schoolproj_image = img
It has to have its own reference to the image
Where should I put that?
:incoming_envelope: :ok_hand: applied mute to @digital rose until <t:1634482146:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
how can i remove this label background in tkinter?
Using PySimpleGUI
Traceback (most recent call last):
File "C:\Users\ckett\PycharmProjects\Calculator\gui.py", line 4, in <module>
[pygui.Button("Start", justification='center')]]
TypeError: init() got an unexpected keyword argument 'justification'
You may set its background to the background of its parent widget.
is it possible to integrate figma and pyqt by anychance
why is it whenever I click my check box, i flashes white and back to normal? How do I get rid of that "effect"? Tkinter.
is there a base widget i can use that has the config method?
i am trying to make a base parent class that houses functions used in subclasses which inherit Frame, Button, Label
Ive used baseWidget, Widget, and Misc but they dont seem to work
they keep asking for a widgetName,i dont know what that is
Why whenever the mouse is hovering over the QLineEdit, the right side is blinking? I use PySide6.
To be honest i have never seen a real life GUI product made by any python GUI libraries
mostly they use electron for interface and python for backend and processing
wa fin maghribi
Hey, what's the best (easiest) way to make same looking gui in Python? Is it smth like tkinter? I never really touched ui on "beauty level" if you know what I am talking about
any tkinter people around?
(note I'm having the same trouble with PyQt)
I'm trying to pop up a short 10sec victory video when a task is complete. a "Good job this 'THING' is done!"
But I can't seem to get the window to close then the player is done playing the video. Everything I've tried thus far closes it half way through playing or doesn't at all. Is there a better way then just putting a 10sec timer on it in case down the line I make them longer? (using tkvideo on the tk version I made)
how do i do that?
U can use after function to destroy the window after 10sec
In tkinter
@sinful pendant
No real different then putting a timer on, as when I put longer stuff, I'll have to go back into the code and change it. Really trying for it to recognize it's done it's action.
Also other stuff will still be happening. Doesn't after work like a wait?
How can i make a GUI for my project using python
Use threading so that program dont freezes
I am also on way of getting malfunction in game app
So tried threading and some text editor thingy
π
Well if this method working well for u then u uave to into ur code to change it
U can use the gui libraries
See this channeltopic there are some of u wanna start woth
I use threading and a timer. Was just hoping for a way to see if something could recognize when it's done playing.
Yess, just a more function(s)
Like in , game monesweeper , as sson as player clicks a mine, after showing all mines, i run endgame function
Is there a good way to flash a animation on the screen for 3-5 sec then toss it? if so then I could just split the stuff up and figure something else out for longer stuff..
What do u mean by toss it@azure talon
pop-up then go away
my main issue is getting that requires time to complete visually to finish when completed.
@sinful pendant
root.after(5000, root.quit)
?
Try this on ur window which shows flashing animation
@sinful pendant
That's no different then what I'm already doing as it requires a programed knowledge of how long it's going to be every time.
Are u displaying different animations on different tasks being done?
as things are completed. yes
So what ucan do is prepare a dictionary
Woth the times, or there might be some method that tells us how long is the video
still puts me back to changing the code every time I put in a new video or animation in the future instead of having a function that I can drop a video into a location and it can be used.
Aah ,i hope ur code is adjustable woth changes
Like, u can make function which pops up window and run,and by giving, arguments for some control
atm I have a setting that I can change the animation / video that plays. It looks at the files in a folder and I can select from them and it'll play when it needs to. My issue is that it just stays on the last frame on the screen.
seems like a strange thing I'm sure, but I am surprised that there's not built in function to end a video when done, I can loop them all day though.
another issue is depending on the device it's on, it take a little longer to load / run the video. When that happens the time / after function time amount will cut it short.
how would I block a QTableWidget's itemChanged signal in PySide6? I've tried blockSignals/QSignalBlocker on the table and its parents but the signals still get emitted. I have an auto column resize connected to it but during initialization the constant resizing hits the cpu for a while
I'm guessing you may not have done gui design before so warning that it won't be easy no matter what framework but qt has qt designer which might make it easier for you
also qt creator
for x in range(2):
for y in range(2):
if x == y == 1:
start_screen.grid(row=1, column=1)
continue
frame = Frames(login_window)
frame.grid(row=y, column=x)
if x == 1:
continue
login_window.grid_columnconfigure(x, weight=1)
login_window.grid_rowconfigure(x, weight=1)
it places start screen on bottom right
why
my tkinter scrollbar is small, how do i make longer?
I haven't make any GUI before can anyone tell me how to start or how can i learn to make one
I need it for my project
If you've connected the signal to a receiver you can temporarily disconnect the signal using QMetaObject.Connection.
This is assuming that QMetaConnection has made its way into PySide6
Depends what library you want to use
I dont have any idea about the GUI libraries the thing is my project is wifi based where i will connect raspberry pico with esp8266 wifi module to receive the data i need
Try to inter
Tkinter*
Ok
Can u give me any jumpstart on that
Can someone help, I am getting something like. Can't invoke wm command,. Application destroyed
you need to show the code as well
Did you call destroy() on your Tk root? As it says, that destroys the entire Tk application, so no more methods will work anymore.
you need to write all the code before starting the mainloop
root = Tk()
root.geomentry("880x897")
root.minsize(870,880)
root.mainloop()
Thank you, I just started learning π
it's alright
geometry, a small typo :)
yeah
Thank you ppl :)
π
Can anyone tell me how can i make a GUI using tkinter for raspberry pi pico
:incoming_envelope: :ok_hand: applied mute to @digital rose until <t:1634642866:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
uhh it might have its own module other than tkinter but you can try running normal tkinter code on it
Hello guys! Not exactly sure if this is the right channel for this question but I'll give it a shot.
I would like to program a, let's say, excel sheet with GUI. I describe it like that, because it really is nothing more than a tool to create a database of a lot of electronic devices and their consumption.
Right now, I just type in the name of the device and in the same row, all the different information connected to it, like the amount of kW it needs, the manufacturer, location etc. The goal is to sum up all the energy consumption of all devices.
The problem is, that every device has a unique identification key. This key can vary from project to project. For example it can look like this: 1-01-FRI-0001-PUM-0001. Building 1 - 1.floor - cooling machine - nr. 1 - pump - nr.1.
I would like to make a tool with GUI where I can set the identification key syntax (amount of numbers, alphabetical symbols etc.) and then be able to add different devices which then are sorted after the kind of device e.g Cooling, Heating, air conditioning etc. In the end I imagine there will be a database/table for every kind of devices (cooling, heating, etc.) but with one database where everything is in it, sorted after categories with a filter function
Is python even good for this? Would another program language be better for this kind of job?
Most successful GUI products use Python as it's administrative program and Javascript(Electron.js) as its GUI interface
and no there is no library in python that could create a GUI that can be unleashed as a modern product
3 packages if you learn you can be best python developer (Javascript/CSS/HTML) for Graphic User Interface, Python for administration of application such as a backend, Java to use as extension in Jpython for functions that needs faster processing. if you can master these mentioned languages you can make any application you want
Vscode and Discord and many other amazing applications were made by Electron.js, Odoo famous ERP desktop application was made by GUI Electron.js and Administrated by python as it's backend.
I am currently struggling with a scrollbar, that should scroll the Canvas ("c" in this case) down.
The scrollbar appears, but is not scrollable. Any Idea why this is failing?
class ServerList:
def __init__(self, master):
self.list_of_elements = []
c = Canvas(master, bg="white")
vbar = Scrollbar(master, orient=VERTICAL, command=c.yview)
vbar.pack(side=RIGHT, fill=Y)
c.pack(anchor=NW)
c.config(yscrollcommand=vbar.set)
server_list = scan_servers("95.156.227.18", 100, 128)
for server in server_list:
create_server_entry(c, server)
root = Tk()
root.title("Server List")
root.geometry("600x600")
ServerList(root)
root.mainloop()
Okey, thanks
Anyone?
In this tutorial, you'll learn how to apply object-oriented programming in Tkinter to make the code more organized.
hope this helps
@royal dove Well, it fixes the unstructured code, which is the result of me testing around. Because any solution, I found, results in the scrollbar appearing, but not doing its job. The bar just fills the whole box and is not movable. Thereby doing nothing.
I've got this window written in tkinter now i want to make it so the user can enter list of users and this will result in something like this:
add;Username@something.com;Rolename1
add;Username@something.com;Rolename2
add;Username2@something.com;Rolename1
add;Username2@something.com;Rolename2
How do i make that username list from tkinter Text gets appended with selected things into csv file?
Ok I'll do it
But
How can i get access to the mainclass attributes?
In the child class?
Do i have to do something like,
ClassVariable = mainclass()
?
And then ClassVariable.attribute.method()
You already have them.
the child class inherits them.
Just create an instance of the child class, and it gets all the properties of the parent class too.
hi i need help in tkinter
so im trying to make this code work but it wont work, idk whats the matter :
def logister():
def submit():
username.delete(0, END)
password.delete(0, END)
identity.delete(0, END)
logreg = Tk()
logreg.title('login/register')
username = Entry(logreg, width=30).grid(row=0, column=1, padx=20)
password = Entry(logreg, width=30).grid(row=1, column=1, padx=20)
identity = Entry(logreg, width=30).grid(row=2, column=1, padx=20)
Label(logreg, text='Username').grid(row=0, column=0)
Label(logreg, text='Password').grid(row=1, column=0)
Label(logreg, text='ID (custom 5 digit number)').grid(row=2, column=0)
submitter = Button(logreg, text='submit your account', command=submit).grid(row=3, column=0, columnspan=2, pady=10, padx=10, ipadx=100)
idk what to do it wont work and im trying to get it work with SQL
how did you change the background
it wont even clear the entry boxes
help?
The variables don't have a reference to the Entry's, they have a reference to the return from the Entry's grid method, create the Entry's and call grid on a separate line.
its already fixed sorry lol
and thanks too btw
respect
Hi
I am using PyQt6
and can't find a way to
put a icon at the taskbar for my app
pls helpp
here is a screen shot :
Hey @fathom cosmos!
It looks like you tried to attach file type(s) that we do not allow (.pdf). 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.
and I am also using cx_freeze to compile as a executable
Do someone knows that what can be the reason that tkinter not able to display image on button but button size is set as per the image dimensions, but image do t show up its blank, and when we click on button the button doesnt responds
Self.images is a dict which contains file path value
A dict having theme as key and a small dict a s values in which keys are the numbers and values are respective paths
Even that commented img line also gives same result when used
The image has probably been garbage collected as there is no reference to it.
keep a reference to it on the button.
add
btn.img = img
Everytime is use same img 2nd time it went i to garbage, even if i copy paste imag and move it so ewhere else
Aah it wont be a problem if i change the image later
Cuz its soduko and you know numbers changeπ€
if you change the image with config then also change the reference on the button to the new image
Ohk
The "client size of a window" means the dimensions of the actual window area, right? Not the window plus border.
(in general terms)
It's the area without the frame with the close button and everything, where you put new widgets usually
Imagine a command prompt window, the entire black rectangle in it is the client area
If you're familiar with Qt, the centralWidget is the same thing that winforms/.net refers to as client size
Yeah, I'm coming from windows forms.
Hi, Can you explain me why the min and the max doesn't work?
there are no numbers in your list, only strings
you'd have to convert them to integers first to get what you want
How to use styles like Material or Universal in Pyside6?
change them to integers, int(number)
hey yall, I want to make a text-based python game that I can ship as an executable, so I want to use a GUI. It's going to be an RPG game so I want to have a list of message "history", so as lore/story is shown on the screen the player can scroll back up and read the past messages (past 100 or so). Is there a PyQt5 object that lets me display something like this (maybe an object that can store a list of things and display them, each thing in the list being a string with a message)?
im not sure how to do it with pyqt5, but i know you can do something like that with tkinter, sorry
how would I do it with tkinter?
Not sure if you like this idea, but you can use a Listbox widget perhaps
Each item inside the Listbox can contain your message
But you are not using tkinter, and you are using pyqt5, so i cannot help you sorry
There is QListView and QListWidget iin Qt
Is pyqt5 difficult to use?
pyqt looks nicer than the others I've seen that's why i would prewfer to use it
Hmm, I prefer tkinter's look
It has a learning curve but it's not that hard to learn, assuming you're familiar wiith OOP already
i have set the qpushbutton size 30x30 and qlineedit size 220x30 but they dont have same height (pls mention me)
How would that look? Disconnect the signal, do the work and then reconnect it to the same slot?
Hi, I'm using QT Designer and I want to know how can I call a new window , without need to import the second .py file in my main code.
I'm having trouble joining the two classes into one file and getting it to work, could someone give me a hand?
The main code:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
##code
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
And the second windows:
class Ui_ErrorWindow(object):
def setupUi(self, ErrorWindow):
##code
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ErrorWindow = QtWidgets.QDialog()
ui = Ui_ErrorWindow()
ui.setupUi(ErrorWindow)
ErrorWindow.show()
sys.exit(app.exec_())
Roughly like this:
sig = self.itemChanged.connect(self.test) # assign the connection to some variable
self.sig_val = QMetaObject.Connection(sig) # save it to the instance in a variable or list
self.disconnect(self.sig_val) # Whenever you want to disconnect the signal
If this is something that happens every time you resize the table you may want to put it in a function
then after the function has finished doiing whatever it does reconnect the signal
then after the function has finished doiing whatever it does reconnect the signal
You're going to have to import it into the main window or another widget thats imported into the main window.
and you shouldn't make a habit out of writing your code in the .py files generated by pyuic
you should create a different file and import the mainWindow from pyuic in there
let me find an example
How does the reconnection happen?
I tried this which disconnects it, but it doesn't handle the signal when I change items after that
class MainWindow(MainWindowGUI):
def __init__(self):
super().__init__()
conn = self.table.itemChanged.connect(partial_no_external(self.table.resize_column_to_contents, 0))
self.sig_v = QtCore.QMetaObject.Connection(conn)
self.mass_insert([["1", 2., 3., 4]] * 5000)
def mass_insert(self, data: list[list[t.Any]]):
self.disconnect(self.sig_v)
for row in data:
self.insert_row(row)
self.table.resize_column_to_contents(0)
self.table.resize_rows_to_contents()
You need to reconnect it manually after you finish with column resize function. I'm not sure if you can reuse self.sig_v for that or not
ah right I misread that
It's more work, but you might want to look at using a QTableView instead of a widget if you're going to have 5k rows
its far more responsive
The realistic maximum is around 300-500 but the startup delay from the signal being connected is very noticeable even with that, which I'm trying to minimize as it's slow enough already with it loading python and Qt
Is there a reason for the QMetaObject.Connection? The connect call seems to return an instance of that already
hmm, then you might be able to get away without that if the disconnect works... It might just be required for custom signals
@eager beacon like subclass?
Yeah, you need to inherit QMainWindow and the UI class
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
what should I change here do use two classes?
i'm trying to pass the second class in my main code, but Idk what I need to do here
any idea why the QSignalBlocker didn't work? When I tried looking at the sender through self.sender() it was some random QTableWidgetItem
something like
from UI_FILE import Ui_MainWindow
from PyQt5.QtWidgets mport MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = MainWindow()
MainWindow.show()
sys.exit(app.exec_())
I dont want to use a secound file to import in my main code
I'm not sure to be honest, I would think it should since the QTableWidgetItems are chldren of the Table
I want to call a second class in my main class in the same file
Then import your second window into the mainwindow file and add the second window as an instance varable and call ErrorWindow.exec() when you want to show it i guess
I have to go, but you really should use a 3rd file to import the 2 UI files into.. It would make your code a lot easier to work with in the long run
I have a chat app in a terminal but i want to make it look better; whats a good libary for this that keeps the terminal style?
i was thinking curses but i want to know if there are other options
I'm curious too. I just looked up Kivy. I have no experience with it im just curious too
haha i was about to say, lets look at the pinned msgs since were clueless
first thing Kivy lol
Yay! im learnding! π
I've used tkinter before and i know kivy is widely used but i like the terminal style of my app rn and i want to keep it that way
Hey, i have trying making a app with pyqt5 and i'm just trying working selenium in background but my gui is stop responding
i have tried QThread but i couldn't
i guess something block threading but i didn't find it
:incoming_envelope: :ok_hand: applied mute to @tight grove until <t:1635119970:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
:incoming_envelope: :ok_hand: applied mute to @final hound until <t:1635126034:f> (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
linus torvalds says he would rather die on the island that do ui stuff , i also feel the same, do anyone of you feel the same , and if not what do you guys think of people like us
Hello ! HELP NEEDED!
Hello world! Is anyone good in Tkinter?
it's better to just ask a question than asking for an expert
i feel same thing
heyo, does someone have experience with pyuic5 code? I need to close the window, but self.close or self.hide wont work. Tried many things but nothing worked for me
Edit: I found a way, if anyone still needs help:
self.closebutton.clicked.connect(lambda: self.function(MainWindow)) - calling a function and giving the mainwindow argument (the mainwindow has the close function)
and then in the function you just call MainWindow.close
:incoming_envelope: :ok_hand: applied mute to @nocturne cliff until <t:1635192671:f> (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
I think UI is the most satisfying thing about programming, because the tiniest details have the power to make your user's day, or to ruin it.
But GUI technologies make me sad.
I would definetely say kivy
I believe you can imitate a terminal with kivy
I already made it with tkinter
good for you
is there any windows xp type ui for python?
I've heard a lot of people saying tkinter looks like Windows XP's style
there are some ttk style themes that look similar to windows xp
Any idea what pyside6 is doing here? After inheriting QObject, staticmethods disappear from the object
class Test(QtCore.QObject):
def __init__(self):
super().__init__()
self.func()
@staticmethod
def func(): ...
leads to AttributeError: 'Test' object has no attribute 'func'
is there a lib that provides asyncio support to tkinter?
I think it is see i managed to make the format almost lookong lioe the one runs on xp
Does anyone know how to make python return a value from the tkinter insert widget ?
Like, I can do print(my_entry.get())
Nevermind I fixed it, it works if I put it inside of a function
What version are you using?
The example you posted seems to work just fine in 6.1.3
6.2.0
hmm, does it work if you try the snake_case and true_property features? I tried it with it disabled in the module but maybe something bled through from others
Oh, probably not.. true_property screws some stuff iirc
actually it appears to be snake_case that causes this to happen
strange, with how it's worded I assumed it should only affect the state in the current module
I'm not sure how it's supposed to work, but I remember that it did have some issues when 6.0 was released.
Apparently there are still some problems with it.
I don't know of any sort of workaround that would allow a static method when importing snake_case/true_property π¦
I really wish they wouldn't have even added the option. After 5+ years of using PyQt/Pyside it just looks wrong to see Qt methods in snake_case
I'm trying to use it and it does look nicer but there are cases with true property where I'm not sure if something was a set_ method or a property; and for snake_case not all names (e.g. signals) got converted
Hopefully it will get sorted out within the next couple of releases. Right now I'm still a little bit uncomfortable starting a new project using Pyside6
And you're right, it does look nicer, becauese it looks like all of the other python code you normally see. What it doesn't look like is every other PySide/PyQt app there is, and that can be confusing.
The only other issue I found related to the features was a method where they overloaded on a property so true property ended up overwriting the existing method
which hopefully gets fixed soon as there was some discussion on the issue I raised after painstakingly logging in into the jira
Haha yeah, reporting the bugs on qt.io can be a pain.
if you don't get a quick response, make sure to check on it every few days until someone triages the report
they love to stick Wont Fix tags on the reports, especially if you don't include an example
Did you code that Mines thing?
how do you make it have options and stuff
can someone draw epycycloids
I have a question about 3D rendering and such
Why is it that Python is considered too slow? Unless I'm mistaken, all of the rendering is happening at machine speed, deep in the undercode. Reacting to user events and then changing the gameworld might be a bit slow but I don't see any reason the rendering itself should suffer
Is there something I'm missing?
Help: tkinter (Tk() related)
In my app i want to give my user an option to able to ake a particular frame in new window, so what should iwrite in my_frame.config(?=newroot)
It's not too slow. It just a myth being spread by people who don't know what they're talking about, and more often than not, have never made a game. Or the old pygame is the only thing they tried.
Often you need to some math on some data and send that information to the gpu every frame, like moving things, collision, moving the camera. And that can be slower than in other languages. In pypy or cython it would not though, so really that mostly apply to the cpython implementation, not python itself. The fastest python game engines still calls a c++ program and have python bindings for it, so that's a good solution too
See, that's always been my suspicion. So long as nothing is getting in the way of the rendering then it shouldn't really matter the speed of the language. Dealing with milliseconds instead of nanoseconds in terms of reaction and computation time seems dramatic but doesn't really make a difference
Hi everyone, I'm looking forward to build a GUI using python because but I prefer using web technologies for the UI. Kinda like electron for Python.
is there any framework/library to recommend ?
XD Well actually
I've been working on building that very framework for a few years now
School has been slowing me down, but I'd like to be done early next year
Or at least in beta
In the mean time you can check this out. With this you can package the browser and application framework in a python app (presumably bundled with pyinstaller)
CefPython lets you call javascript directly from python, and vice versa, so you can establish pretty clear cut communication between the front and back ends
But you still have to code the UI in HTML/CSS, attach the event listeners in JS and actuators in JS, and do the meat-and-pototes computation in python
wow, I'll check it out
XD Yeah
It would be nice if there was a simpler answer
HMU if you need anything
Python EEL
uses HTML and CSS with python
a bit like electron π
text is overlapping Tkinter canvas HELP!!!
Would the only option for a checkbox item in a QTableWidget be to create a custom delegate? I was hoping to avoid implementing the painting
Use Label.config(text=TEXT)
That will change the pre existing and overlapping wont occur
okay thanks
Noobish question here: are there any 3D rendering libraries for Python similar to Three.js?
Or Unity, I suppose. Something that uses meshes with vertices, normals, uvs, etc. and also textures
you may like using htmx for sending fragments over the wire. ie. https://github.com/byteface/htmxtest/blob/master/app.py
and use pyinstaller to bundle your server.
I got most of it, but I'm having trouble figuring out how to get the item's foreground color (set by setForeground) in the paint method, and then also checking whether it's being edited - from the two state options I found in the docs one doesn't change and the second one doesn't exist
Thanks @unique forge and @digital rose. it's really helpful
you're very welcome
hey i was wondering whether when wanting to design different screens for a gui (ie, login screen that moves to a main menu, or a high scores screen) should these each be separate classes?
in tkinter
and from there once you press on a button or a function finishes it calls the next class
the means by which the user and a computer system interact, in particular the use of input devices and software.
You are using Discords User Interface
user interface is the buttons and stuff on the screen
how can i close the gui app.close(), then run it again without actually running it, like restart?
Have a frame widget that you pour into everything you want to "restart", create a function that packs and configures stuff in that frame and have the frame packed as well, then make a "restart" function that deletes this frame and calls your function that creates and packs this frame
v
You cannot change the master of a widget
Do I have to pay if I make a UI using pyqt5?
Eel
Update existing text, instead of making new ones
yea that is better
No, IIRC, but you will have to buy a commercial license or sth if you plan on releasing it as a paid app.
I'm trying to override a drag event for a QListWidget with one that attaches an override, in doing that, i have to also redo the pixmap, how do i get the visual coordinates of the QListItem? (considering the scroll and everything)
Hey how to make tkinter Label update text itself every time text change,have counter in another file that counts mouse clicks want to show that in GUI?
Hello, how can i bring scrolling to the text in tkinter?
does anyone knows hoe to work with tkinter? Can't solve the problem for couple of days now... #help-honey
Hi guys, could someone recommend me libraries/frameworks to create beatifuil GUIs?
Hi all, I'm using Python's tkinter and ttk to make a combobox, but no tutorials seem to cover reading typed entries to auto search and auto drop down the menu as the user types... any ideas on this? kinda like the dropdown autofill/suggestions in Google for example, as I have an insane number of entries for the user to search through.
whats up fellas, is anyone familiar with QT designer? im trying to add an image, which i completed and when i execute the script its formated like this:
screenshot:
you might be interested in the ttkwidgets module
you can install it with pip install ttkwidgets
I have a label with the interaction flag as py label.setTextInteractionFlags(qtg.Qt.TextEditorInteraction)
Is there any way I could get a edit done signal?
:incoming_envelope: :ok_hand: applied mute to @ripe gazelle until <t:1635752249:f> (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
Any help in #help-mushroom would be appreciated
Almost there, trying to make vscode's-like pop up menus in tkinter C:
:incoming_envelope: :ok_hand: applied mute to @west zealot until <t:1635796527:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
wait is tkinter in built in python
Nice idea
Import the variable?
Which text
Ask your question
PyQt, Kivy
There is a external module that does this
great
nice
Its natively written in TCL, tkinter is a python wrapper around it
thanks C:
tkinter is no bad, but will require some workaround :)
ok
i heard about proxylight
a tkinter designer tool
but when i try and use figma
i dont get how to add buttons
or anything
the tutorial is just a sped up of him doing the only thing i dont understand
Yeah I did eventually stumble upon the ttkwidgets module which fixed that right up with "AutocompleteCombobox"!
:incoming_envelope: :ok_hand: applied mute to @frank jasper until <t:1635897929:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
Hiiiiii I need to make python quiz and want a layout
hey
is there a way to embed those green rectangles in login form, so that they are visible only within this gray rectangle area?
I would like everything outside that gray area to be invisible, to cut the rest of those green rectangles
is it even possible in Figma? I tried moving objects to the background, to the front, make them normal, overlay etc. but nothing helps
hey everyone,
I have a question in regards with Pyglet if anyone has had experience using the module..
I have been able to load my gif to a window that is proportioned according to the gifs image. I am now trying to create a full screen window with the gif to fit the size of the monitor but have been unsuccessful getting error messages and such and at the moment just have the animate gif in the corner not scaled to full screen with a purple background. Below is the code including the original code for the small windowed gif that is commented and below it is the code for the full screen gif
import pyglet
from pyglet.canvas import get_display
# 'Load animation'
# animation = pyglet.image.load_animation('Goober#13427G.gif')
# animSprite = pyglet.sprite.Sprite(animation)
# 'Set width and height of window'
# w = animSprite.width
# h = animSprite.height
# 'creates window dimensions according to WxH of gif'
# window = pyglet.window.Window(width=w, height=h)
# r,g,b,alpha = 0.5,0.5,0.8,.05
# pyglet.gl.glClearColor(r,g,b,alpha)
# @window.event
# def on_draw():
# window.clear()
# animSprite.draw()
# pyglet.app.run()
'Load animation'
animation = pyglet.image.load_animation('Goober#13427G.gif')
animSprite = pyglet.sprite.Sprite(animation)
'attempted code to scale'
# H_ratio = max(animSprite.height, display.height) / min(animSprite.height, display.height)
# W_ratio = max(animSprite.width, display.width) / min(animSprite.width, display.width)
' Get display and create a fullscreen window according to screen'
display = get_display()
screens = display.get_screens()
window = pyglet.window.Window(fullscreen=True, screen=display[1])
r,g,b,alpha = 0.5,0.5,0.8,.05
pyglet.gl.glClearColor(r,g,b,alpha)
@window.event
def on_draw():
window.clear()
animSprite.draw()
pyglet.app.run()
I've been trying to figure out how to get the image to scale to fullscreen but have had no success unfortunately
hello
i have a trouble\
i can't create Qwidgets in my project by using loop
thank you in advance
self.pages_creator()
def pages_creator(self):
for i in range(10):
self.cheat_page = QtWidgets.QWidget()
self.stackedWidget.setCurrentWidget(self.cheat_page)
Making an emoji keyboard for windows with PyQt5, is there a window flag or some other way to not transfer the focus to the newly created PyQt window when it initializes and shows?
Picture to explain the idea further, the search bar gets the focus, aka anything that's typed goes there and i would rather have the focus stay wherever it used to be
(the grey background text editor is separate application)
Kinda got it working by getting the hwnd of the pyqt window and the old window and manually switching the focus to the old window after initialization but that seems kinda bodgey way of doing it
class App(tkinter.Tk):
def __init__(self, *args, **kwargs):
tkinter.Tk.__init__(self, *args, **kwargs)
container = tkinter.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for f in (Home, Search, Jobs):
page_name = f.__name__
frame = f(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("Home")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
if __name__ == "__main__":
app = App()
app.geometry("800x500")
app.resizable(height=FALSE, width=FALSE)
app.title(app_title)
app.mainloop()
class Home(tkinter.Frame):
def __init__(self, parent, controller):
tkinter.Frame.__init__(self, parent)
tkinter.Frame.__init__(self, parent, bg='#FFFFFF')
self.controller = controller
img = tkinter.PhotoImage(file=image_path)
self.label_image = tkinter.Label(self, image=img).pack()
problem is the image is not visible
im assuming that light grey is the view for Label but image is not visible
any help is appreciated
keep a reference to the image so it is not garbage collected.
class Home(tkinter.Frame):
def __init__(self, parent, controller):
tkinter.Frame.__init__(self, parent)
tkinter.Frame.__init__(self, parent, bg='#FFFFFF')
self.controller = controller
img = tkinter.PhotoImage(file=image_path)
self.label_image = tkinter.Label(self, image=img).pack()
self.label_image.img = img
gotcha
although correct code would be
class Home(tkinter.Frame):
def __init__(self, parent, controller):
tkinter.Frame.__init__(self, parent)
tkinter.Frame.__init__(self, parent, bg='#FFFFFF')
self.controller = controller
img = tkinter.PhotoImage(file=image_path)
self.label_image = tkinter.Label(self, image=img)
self.label_image.image = img
self.label_image.pack()
also it worked π
anyone can help with pyglet?
Hi, does someone know how can I show the current screen in a GUI? Which functionality is this or which libraries can do this, thanks
I've written some code recently that stretches the viewport keeping a base aspect ratio, but that should be easily transferred to your gif: https://github.com/Square789/PydayNightFunkin/blob/main/pyday_night_funkin/graphics/pnf_window.py#L24
Since sprites work with a scaling factor, I think (when copypasting and keeping the variable names the same) animSprite.scale_x = (viewport_width / animSprite._texture.width) and the same for the height should be able to do the trick
tgt_wh_ratio would probably also need to be set to the GIF aspect ratio if i didn't take a wrong turn in my thinking
hmm, I'm looking at the code and its quite different from what I wrote but im assuming the CNST import from the import pyday is a animation youve loaded?
it's effectively just 1280/720
Do you want to keep the gifs aspect ratio or do you just want to stretch it to fill out the window?
if i stretch it the pixels will become distorted im assuming right?
if so then id keep the aspect ratio accordingly so it stays true to image and just fills the screen
that is what this code should be able to do, although i guess it may be too complicated; is your window resizable?
for my code? it doesnt exactly create a window per say it. It creates a full screen window that isnt closable until the code is interrupted. The first half of the code is a windowed version that is closeable via the "x" but its created according to the size of the image
hm, i replaced the
CNST.GAME_WIDTH / CNST.GAME_HEIGHT variables in
tgt_wh_ratio = CNST.GAME_WIDTH / CNST.GAME_HEIGHT
with my own width and height of the image along with loading my animation and while the code ran nothing happened let me check with debug what occured
ah right, i probably should've read your sample, my bad
Basically that means you don't really have control over the dimensions of the window though, I don't know if the on_resize handler works with fullscreen windows, but try something like
tgt_wh_ratio = animSprite._texture.width / animSprite._texture.height
@window.event
def on_resize(w, h):
cur_wh_ratio = w/h if h > 0 else 999
if cur_wh_ratio > tgt_wh_ratio:
...
animSprite.scale_x = viewport_width / animSprite._texture.width
animSprite.scale_y = viewport_height / animSprite._texture.height
Although it should be possible to just use animSprite.scale to scale it equally along both axes, but i am too tired to figure out the math for that right now
Probably best to use the _texture's width/height since otherwise the sprite will return its scaled width, which is exactly what we don't want when figuring out the correct scaling
I see
I'm a tad more confused trying to relate both codes to make it work but im looking at the pyglet scale documentation that ive read before but going to attempt something with that hopefully something will work with it
Iβm brand new to pyglet so im not sure how _textures work but will be looking at the docs when I get back from lunch
i need to make this button open local file that i choose and open it on the same window not a new window
import os
import tkinter as tk
from tkinter import Toplevel, ttk
from tkinter import filedialog
root = tk.Tk()
root.title("GUI")
root.iconbitmap('icon.ico')
root.option_add("*tearOff", False) # This is always a good idea
root.geometry("1000x600")
root.columnconfigure(index=0, weight=1)
root.columnconfigure(index=1, weight=1)
root.columnconfigure(index=2, weight=1)
root.rowconfigure(index=0, weight=1)
root.rowconfigure(index=1, weight=1)
root.rowconfigure(index=2, weight=1)
root.resizable(False,False)# Create a style
style = ttk.Style(root)
Import the tcl file
root.tk.call("source", "proxttk-dark.tcl")
Set the theme with the theme_use method
style.theme_use("proxttk-dark")
#Button Function
def openfolder():
newwindow = Toplevel(Frame1)
d = tk.IntVar(value=2)
Frame1 = ttk.Frame(root, padding=(40,0,0,10))
Frame1.grid(row=0, column=1, padx=0, pady=(50,10), sticky="nsew", rowspan=3)
Frame1.columnconfigure(index=0, weight=1)
Button = ttk.Button(Frame1, text="Open File",style="AccentButton",command=openfolder)
Button.grid(row=1, column=0, padx=200, pady=10, sticky="nsew")
@amber roost managed to scale the image accordingly to the screen and it works wonderfully(left screen is full screen image),
thanks for the help
That looks like you just hardcoded the scale to your specific screen size, this is probably going to fail on other monitors
i did indeed lol
i needed to understand the scaling function first
now i have to figure out how to implement it with the displays accordingly
this is the code currrenly @amber roost :
'Load animation'
animation = pyglet.image.load_animation('Goober#13427G.gif')
animSprite = pyglet.sprite.Sprite(animation)
'Set width and height of window'
w = animSprite.width
h = animSprite.height
'Scale image to screen'
animSprite.scale_x = 3.2
animSprite.scale_y = 1.71
' Get display and create a fullscreen window according to screen'
display = get_display()
screens = display.get_screens()
window = pyglet.window.Window(fullscreen=True, screen=screens[1])
r, g, b, alpha = 0.5, 0.5, 0.8, .05
pyglet.gl.glClearColor(r, g, b, alpha)
@window.event
def on_draw():
window.clear()
animSprite.draw()
pyglet.app.run()
my issue is i get this error saying that for example "win32display" has no attribute height when I try to scale it with that
thats why i went the route of hardcoding for now
actually thinking up an example, i got something significantly less convoluted working:
animSprite = pyglet.sprite.Sprite(animation)
SPRITE_W = spr._texture.width
SPRITE_H = spr._texture.height
SPRITE_WH_RATIO = SPRITE_W / SPRITE_H
...
@window.event
def on_resize(w, h):
wh_ratio = w / h if h > 0 else 999
if wh_ratio > SPRITE_WH_RATIO:
spr_factor = h / SPRITE_H
else:
spr_factor = w / SPRITE_W
animSprite.scale = spr_factor
This forces the sprite to the bottom corner though, may not be exactly what you want
If you get an error mentioning Win32Display, you are not accessing windows but displays (which from what i can read on the docs are effectively window containers)
the image you sent looks stretched, in which case you don't really need to compare aspect ratios and can just use this directly:
@window.event
def on_resize(w, h):
animSprite.scale_x = w / SPRITE_W
animSprite.scale_y = h / SPRITE_H
Hi Guys
Could I opinions on how I might make my GUI look better
I have a design, but I think the input fields look boring and plain
One small change you could make that would make a big difference is to align the labels next to the input boxes to the right.
I'd also increase the height of each of the LineEdits by a few pixels
adding a border-radius of 2-3 pixels on those inputs after increasing the height would be nice too
Theres a lot of empty space to the right on the inputs, maybe think about reducing the overall width of the UI
You also don't need to label each button at the bottom with BUTTON, its obvious those are buttons
Thank you!
What library/OS are you using?
Tkinter
What is this local file
Are there any ways to run python scripts using voice assistants. Google assistant would be ideal but I would settle for Bixby or Alexa
anyone have same issue when upgrade to macOS monterey? which is the tkinter windows showing all black when using it.
I think you might need to download a version on python from python.org and try using that version to run the app
@unreal rivet if you install python with brew i think you will also need to install tk with brew. brew install python-tk
I'm executed brew install python-tk with no error. but still got the same result
did you install python 3.9 with brew?
is new macOS cause that? I'm remembered that there's no problem in BigSur
I mean, maybe... It could be something broken in that version of Tk, or it could be that apple broke something
yeah, I'm install python3.7 through brew, and I'm try using python3 (XCode tools kit) which is working....
π€
why 3.7?
cause I'm remembered that openCV or dlib reqiured python3.7 or python3.8, but the in-built python already got python3.9...
:π’
I'm pretty sure that brew install python-tk defaults to the 3.9 version of TK which would require python 3.9 to run
maybe? I could install python-tk@python3.7 ?
I don't think that exists
right.................
why? but I used to use tkinter with python3.7 before.........
π€
Yeah, In 3.7 tk was bundled with the brew python
but there may be something that hasn't been updated for the new OS in that version
just try brew install python@3.9 and try to run the tk script with 3.9
even if the other libraries aren't supported you should be able to get an idea if it's the Tk/Python version that is causing the issue and go from there
I'm guessing that it will work, since you were able to run it through XCode
I remember a while back when Mojave introduced dark mode there was a somewhat similar problem with PyQt5
any easy gui libaries
which library
Hi guys
I need to delete a line and a line break from Text
Example: self.text.delete(f'{self.index} linestart', f'{self.index} lineend') # + char \n
#search(), insert(), delete() method, Tkinter Text
Thanks
#help-peanut message
What classes should be defined for this program?
#help-peanut message
how to know type of event in tkinter like when i enter a widget or leave it, both causes triggers the same function but i want the function to be dependent on the type of event so how can i detect that?
and how do i create a horizontal paned window in tkinter like side by side and not top to bottom?
i tried to do it with 1 paned window and 2 labels but it turned out to be stacked instead of being side to side
Are you sure these aren't two different events?
No they are 2 different events for sure
Like when I print(event) it shows something like
<Event Enter blah blah numbers>
Or
<Event Leave blah blah numbers>
But IDK how to use that
Bind to these events with a different function
can I talk about tuis here?
yea
I needs help
can someone help me make this
this is just one part of it
here is the requeriments
Hey @slender mica!
It looks like you tried to attach file type(s) that we do not allow (.pdf). 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.
Anyone can bring some clarity to my code as to why when I attempt to scale my gif to full screen half the screen is white while the other is the gif(animation)? This is using the Pyglet python module.
Here's my code along with an image of the issue:
'Load animation'
animation = pyglet.image.load_animation('Goober#13427G.gif')
animSprite = pyglet.sprite.Sprite(animation)
# 'Scale image to screen *harcoded*'
# animSprite.scale_x = 3.2
# animSprite.scale_y = 1.71
' Get display and create a fullscreen window while scaling gif to screen'
display = pyglet.canvas.Display()
screen = display.get_screens()
H_ratio = max(animSprite.height, screen[1].height) / min(animSprite.height, screen[1].height)
W_ratio = max(animSprite.width, screen[1].width) / min(animSprite.width, screen[1].width)
animSprite.scale = min(H_ratio, W_ratio)
window = pyglet.window.Window(width=screen[1].width, height=screen[1].height, fullscreen=True, screen=screen[1])
r, g, b, alpha = 1, 1, 1, .5
pyglet.gl.glClearColor(r, g, b, alpha)
@window.event
def on_draw():
window.clear()
animSprite.draw()
pyglet.app.run()
Hey if anyone in here has a moment....I just started learning how to use tkinter, and well....I hate it. lmao so is there a more friendly gui that I can write through python? Or just something different?
You can try PyQt or kivy
well any one can help me in tkinter GUI i dont why my black frame got disappear when i pack red to it
#Import the required library
import tkinter as tk
from tkinter import ttk
#Create an instance of tkinter frame
win = tk.Tk()
win.geometry("800x500")
nb=ttk.Notebook(win)
frm1=tk.Frame(nb,bg='grey',width=800, height=450)
frm2=tk.Frame(nb,bg='blue',width=800, height=450)
nb.add(frm1,text='General')
nb.add(frm2,text='2')
frm_gen=tk.Frame(frm1,bg='black',width=210, height=120)
frm_gen.pack()
nb.place(x=0,y=0)
#frm_pro=tk.Frame(frm_gen,bg='red',width=20, height=12)
#frm_pro.pack()
win.mainloop()
i just commented out that here in my code so when u run that it will show you a black frame in the general tab
but when i add red frame to it black frame just disappear only red frame will display
in short i wanna create frame(red) inside a frame(black)
Are there any places that share already made tkinter gui snippets?
Also wonder that too
same
try look "pyqt5" i didn't learn much but looked better, also there is a editor where u can drag and drop your UI items
pyqt5? I will look into that later tonight! Thank you!
no prob my dude
anyone know a good package for software for software development, I want to add images, buttons, text (with custom fonts (I have the font file in the folder))
What is the proper way to center items in TK?
Managed to get them centered horizontally using columns, but vertically is the issue
Have you tried using the justify/anchor?
Eh couldnt figure out how to make them work
username_label = ttk.Label(root, text='KorisniΔko ime:',font='Times 15')
username_label.grid(row=1, column=2, pady=10, sticky='EW')
username_label = ttk.Entry(root)
username_label.grid(row=1,column=3, sticky='EW')
password_label= ttk.Label(root, text = 'Lozinka:',font='Times 15')
password_label.grid(row=2,column=2,pady=10, sticky='EW')
password_label = ttk.Entry(root, show='*')
password_label.grid(row=2,column=3, sticky='EW')
login_button = ttk.Button(text="Log in!", style="Accent.TButton")
login_button.grid(row=3, column=2, columnspan=2, padx=5, pady=10, sticky="nsew")```
This is the code in question
I've got columns declared as py root.columnconfigure((0,1,2,3,4,5), weight=1)
Yeah, just a second
Here it is: https://pastebin.com/7SNACguG
Pastebin
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.
check dm's
What you may need to do is call root.rowconfigure(i, weight=X) to specify which row needs to resize when the window does. By default it won't stretch at all. Usually you'd set one to have a weight of 1.
Hi, i have been searching for hours but i cant find the solution to saving my tkinter gui screen as a pdf... can anyone please help
May i ask What is the reason to do so?
Im doing a quotation system and planning to save it directly instead of doing it in excel
hey, im wondering if anyone here knows how to make a read-only text box in tkinter? thanks,
actually i was trying to add Label using a list containing strings, and add a click event to it, but it only registers click event for the last element from the list.
for user in users:
user_label = Label(self.chatApp,font="Whitney 10 bold",text=user,bg="#23272A",fg="#FFFFFF")
user_label.place(relheight=0.05,relwidth=0.2,relx=0.78,rely=current_rely)
user_label.bind("<Button-1>",lambda event:self.createNewChat(user))
user_label.bind("<Enter>",lambda event:user_label.configure(font="Whitney 10 bold underline"))
user_label.bind("<Leave>",lambda event:user_label.configure(font="Whitney 10 bold"))
print("binded")
current_rely+=0.08
self.searchResultLabels.append(user_label)```
ping if anyone responds
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("converter")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
feet = StringVar()
feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))
meters = StringVar()
ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, textvariable="Calculate", command=calculate).grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, textvariable="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, textvariable="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, textvariable="meters").grid(column=3, row=2, sticky=W)
root.mainloop()
hey so whats supposed to happen here is that 1 button, 1 entry, 3 labels should show up
but the label doesnt show up for some reason. how can i fix this
no error, i get this
hey hey, i got a little problem with qtpy and input mask. Its possible to set an placeholder text and an inpust mask at the same time?
I have made a menu i tkinter. But want to import it into another tkinter file, without it creating two windows. Does anyone know how to do that?
i use Tkinter , and wonder about flow control for layout , i also consider flow control for disabled kids with minimal movement - i want to learn and cross compare
text variables should not be strings
Is there any way to easily "sync up" widgets in Qt? I have a layout I add to all the tabs of a TabWidget and I'd like changes in one of the layout's widgets to propagate to others
or would I just need to interconnect them
Hey not sure if you got an answer or not but this can be done pretty easily in PyQT or PySide
thanks for reaching out but i found someone that can do it for me thanks tho
Is it better to use React or Next for the UI of a project that needs a GUI for loading video feeds of collected localhost of ESP32 Camera feeds?
Iβm wanting to have wireless cameras setup for monitoring fish tanks, that will also send temperature data, i want to have βpagesβ setup so i can have data per tank βpageβ displayedβ¦.
Also a video feed.
Should someone just create a react app, and have it as the opening folder on a PI? Or, is tkinter better?
I'm having trouble with PySimpleGUI. I'm trying to populate a table with this data:
[{'sku': '12345', 'name': 'Black Lotus', 'qr_url': 'https://integromat122720.s3-us-west-1.amazonaws.com/images/newscanner/qr/12345.png', 'series': 'Unlimited Edition', 'condition': 'LP', 'record_id': 'recphdbalhMswaejy', 'card_index': '2ED__Black Lotus', 'qr_label_url': 'https://integromat122720.s3-us-west-1.amazonaws.com/images/newscanner/qr/file.jpeg'}, {'sku': 'ABC-123-455', 'name': "Gaea's Cradle", 'qr_url': 'https://integromat122720.s3-us-west-1.amazonaws.com/images/newscanner/qr/ABC-123-455.png', 'series': "Urza's Saga", 'condition': 'LP', 'record_id': 'recB2S6UhpYrrZFb3', 'card_index': "USG__Gaea's Cradle", 'qr_label_url': 'https://integromat122720.s3-us-west-1.amazonaws.com/images/newscanner/ABC-123-455/qr_label_ABC-123-455.jpg'}]
I have a headings dict also: headings = ['sku', 'name', 'series', 'condition']
Then for the table I start it with:
[sg.Table(values=listvalues, headings=headings)]
But the data are all shown in the first column, not in their respective columns
would appreciate any help
i figured it out
it doesn't read the keys, so you just have to put in the raw values
a list of lists, not a list of key/values
Im working on a clock in tkinter canvas (need canvas because I have an image background)
canvas1 = Canvas( root, width = 800 ,height = 600, bd=-2)
canvas1.pack(fill = "both", expand = True)
# Display image
background = canvas1.create_image( 0, 0, image = bg, anchor = "nw")
# Add Text
clockText = canvas1.create_text( 200, 250, text = "Welcome")
def clock():
hour = time.strftime("%H")
minute = time.strftime("%M")
second = time.strftime("%S")
suffix = "AM"
if int(hour) > 12:
suffix = "PM"
hour = int(hour)-12
else:
suffix = "AM"
text = str(hour)+":"+minute+":"+second+" "+suffix
canvas1.itemconfig(clockText, text=text)
canvas1.after(1000, clock())
When I run this I get this error:
RecursionError: maximum recursion depth exceeded in __instancecheck__
Anyone know how to fix?
Maybe you meant to do canvas1.after(1000, clock) instead?
Np. That passes the function itself rather than calling it and passing its return value
ohh
@sudden coral do you know how to scale the text with the window so its a certain percentage (I dont know how big the screen, I will be using is)
No, sorry. I am not familiar with tkinter. I was just able to spot that error you had cause it was a more general mistake, not specific to tkinter.
ohh ok
there's little to no libraries that give built-in support for scaling text. you'll have to take the window resolution into account for this.
if you don't know the dimensions of the window, it's not hard to get them either:
width, height = window.winfo_width(), window.winfo_height()
base_res = 1024, 740
width_perc = (width / base_res[0]) * 100
height_perc = (height / base_res[1]) * 100
scale_perc = ((width_perc + height_perc) // 2) * 100```
Ik, the monitor is an old one I have and its a different pc as what im testing
^ a simple formula for taking out the scale factor (which i found online).
Does this give pixel size?
apparently, yes.
Okay tysm, ill test when I get home from school tomorrow
how to make something like this using Tkinter?
I suppose using a for loop and grid would be best?
Yes
Y not
I asked a 'How to' question but I got Yes/No answer
Show some code that u have so far, then
not alot actually
not very good with tkinter
here i what i've so far (before i went for a big break)
import tkinter
from tkinter import EW
from src.utils.log import Log
class One(tkinter.Frame):
def __init__(self, parent, controller):
tkinter.Frame.__init__(self, parent, bg='#ffffff')
self.controller = controller
parent.grid()
# Title text label
tkinter.Label(self,
text="Application Form",
bg="#194159", fg="#ffffff",
font=("Noto Sans", 21, "bold"),
).grid(sticky=EW)
self.grid_columnconfigure(0, weight=1)
tkinter.Label(self,
text="Step 1 - Basic Information",
bg="#ffffff", fg="#194159",
font=("Noto Sans", 14)
).grid(sticky=EW, pady=16)
hey so i am trying to add frames inside a Toplevel window, im new to tkinter and is there any way to set a fixed height for the frame? i am using grid for the placements of the frames
you can specify the dimensions when declaring the frame:
some_frame = Frame(master, width=500, height=500)
and if you don't want the frame to cross those dimensions,
some_frame.grid_propagate(False)
you need to really specify what exactly you want to do (keeping the reference GUI in mind) - i.e something like "similar widgets", or "the widget placement" or maybe "the color scheme" to begin with.
if you just want to place the widgets in a similar manner, then yes, grid is exactly what you need.
What signal or event do I have for selection change in PySide2?
most likely itemSelectionChanged, which widget are you using?
QListWidget
I was trying to search for that
but they named it selectionChanged
took me a while
I think thats only available if you're using an itemSelectionModel
itemSelectionChanged is the signal thats emitted when the focus changes from one item to another in a list/tableWidget
That happens not to be in pyside2
ohh, this is hella weird, it's just that my intellisense isn't picking it up
maybe it has something to do with the way it's C bindings are made
Oh, yeah... don't depend on that for the signals. The stubs aren't generated properly for them, so sometimes they will show up, other times they wont
always check the docs
thanks chris!
Is there a guide to completely and correctly install PySide6?
With the designer working completely and stuff?
Not talking about specific problems, but just generally a βthis is what you have to doβ and /or βthese errors are normal and do not mean you installed it wrong or missing somethingβ
I think a normal pip install should work
Starting the designer, the extra example widgets arent in there and previewing python code does not work (the last one could be normal from what I remember)
I know it needs to do something with the env vars, but finding that info doesnβt really work
ah I wasn't aware there was more to the designer than the basics as I don't use it
Its not that I need it, it is more that this is the stuff that I see that errors and makes me suspicious that stuff that I not see could error as well. So I want to make sure that my setup is completely done right.
Kivy question:
Tkinter has a function where when you grid something you can place it in a specific row e.g. .grid(column=2)
I want to create a row with 2 buttons and only have one widget like this
text
button button
How could I do this in kivy?
What do you mean 2 buttons but 1 widget... example looks like 3 widgets as well
Please tell me what to do in this situation? I did not find it in Google. I apologize in advance if I wrote to the wrong channel
How would I go right aligning or auto scrolling text in a QStatusBar? I have a relatively narrow window and want to display information like network errors to the user through it, but those can be longer and the relevant part of the message is on the right
depending on how nice it should look, you can use a custom label with a paint event to drawText and a timer when fired sets the position of the text further to the left until the message has been completely scrolled across the screen. You can use QFontMetrics to get the width of the text
If it were me and I was feeling lazy I would just use a timer connected to a method that sets the text and in the method use slicing to remove letters from the front until the entire message has been scrolled.
go back to your UI file and make sure the name is correct, if it is, that means the UI file was generated before you saved the name.
ah, was hoping to avoid implementing something like that as it usually ends up being more complicated than it has any right to be but guess I'll bite the bullet; at least it's non critical and easy to replace the status bar with
The method that uses slicing to show less and less of the string everytime the timer fires should be pretty simple to implement and should look alright. You might need to use a fixed width label to prevent the text from moving further to the right when the string gets too short
was hoping to also mix in some kind of a "i'm busy doing something" indicator so I could do that with the repaint
I've seen a couple different repos on gh that have circular progress bars, you could just use one of those, or just use a label with a timer to animate some slashes/pipe to make it look like its spinning
Yeah the simple text one was the first thing that came to mind, just something to keep the user aware that things are happening while it's waiting for a long running job
Another problem I'm having is that I couldn't find how to get a colour set through a QTableWidgetItem.setForeground in a QStyledItemDelegate's paint method
I'm not sure I understand.. Why are you trying to use setForeground when you can use the paintEvent?
I mark items as "done" by setting their colour to grey through setForeground, then for some coloumns I have a custom item delegate for checkboxes
within the item delegate's paint event I couldn't find a way to access the colour set by setForeground
this is how the delegate looks now https://paste.fuelrats.com/iqakequzer.py
well I badly copied it but the missing methods are only for the focus rect and figuring out where to put the checkbox
Ohhh, okay. the delegate is only the checkbox.. I thought each item was drawn from a delegate.
I'm not sure how do do it from there, maybe a signal to fire when its checked thats received in the QTableWidget?
I've only used delegates a few times and I don't think I've ever tried what you're doing, but I'll double check to see if I have some code after I get my kid in bed.
I've looked through the docs a couple of times now and I'm not sure if I'm missing something obvious or if it's something complicated. But there has to be the way as the defaults handle it just fine
Anyone know how to use a custom font on linux and windows for tkinter?
Sorry that took so long - Let me read this again and I'll check my code.
Ohh, okay.. I read that wrong the first time... If you just want to get the color you've already set then its just: index.data(Qt.TextColorRole).color()
anyone know how to make a gui that updates from a webpage and displays things like stock prices etc?
RxPy maybe
atleast thats what i would use but there other ways u can implement auto-update
ty i'll try to get this working. it's been a goal of mine to create a small application that basically is an alternative to tradingview because i hate that you have to sub to tradingview to get good charting
Thats an ambitious project
thats what they said bout Elon Musk π
yeah and tbh i'm not sure i can do it. i started learning python a few weeks ago, but i have 3 years experience in java so it's really just learning syntax and different names. i have no time frame on when it's gonna be finished but idrc. i wanna make it donation based like ad block or even just a one time payment and sell ad space instead of doing a subscription to get the most basic services
the only reason i'm switching is because java is so antiquated that i don't wanna be left behind
and the reason i'm doing application based approach instead of web based is because webull moved into the application space and has kinda dominated the game since they started
How can I enable this drag and drop / rearranging inside a grid layout?
https://i.gyazo.com/44b39d3388b8d4c4a0475eb1412f700a.gif
Your best bet is going to be using PySide/PyQt and PyQtGraph. It already has a lot of plotting capabilities, so you won't have to do everything from scratch.
You can use requests to pull the html or data from an API. If you have to extract the data from the html you can use bs4.
tysm this gets me started way faster than from scratch!
Help me please, i have created my own function, but terminal says os doesen't have 'mkfifo', what i need to do to repair that?
def buildverssion(version, src):
path = os.path.join(".ver",version)
os.mkdir(path)
path = os.path.join(version, src)worksheet = Scaffold(version,src)
worksheet.getversion()
os.mkfifo(path)
buildverssion("1.0","atributes.json")
but i get that output
AttributeError: module 'os' has no attribute 'mkfifo'
How can I enable this drag and drop / rearranging inside a grid layout?
https://i.gyazo.com/44b39d3388b8d4c4a0475eb1412f700a.gif
Thin has nothing to do with user-interfaces.
https://docs.python.org/3/library/os.html#os.mkfifo
Availability: Unix.
What should I choose for my gui application? dearpygui or pyside/pyqt
What about plain old boring and built in tkinter?
Depends on your project and requirements
idk why but the rxpy import isn't working for me
Peace be upon you, where is the Arab technical support for tkinter?
i need technical support for tkinter
Please, answer me privately
ah I wasn't aware there were that many roles for data, thought it only did the contents in different roles. That works now, thanks
Is there a way to open a python software using a windows shortcut?
like if I wanted to open a tkinter project I made with a shortcut such as ctrl + shift + g
Copy the full path to your python file (shift-right-click on the file, "save as path")
Somewhere in a folder, right-click in the empty space, "New", "shortcut".
Type python and the path to your file.
Save and exit.
Alt-double-click on the new shortcut to see its properties.
In "Target", you should see that the path to python has been filled in. If not, replace it with the full path to python.exe.
Target should look like "C:\python310\python.exe" "C:\scripts\myscript.py". Basically it should be a valid command-line call.
Delete the content of "Start in" (or change it to the folder that contains your script, ie what you want the CWD to be).
Click OK.
Double-click the shortcut to test it works.
Now, if you want to assign a keyboard shortcut to it... I didn't manage to make it work, but this is the theory:
In the shortcut Properties, highlight "Shortcut Key" and enter the keybind you want.
Apparently this will only work if you register the shortcut in the Start menu:
In Windows Explorer, put this in the address bar: %appdata%\Microsoft\Windows\Start Menu\Programs
Copy your shortcut into that folder.
Reboot (or log out and in).
Hello everyone. Anyone experienced in tkinter....?
I'm not, but lots of people are. Why do you ask?
#help-falafel in need of QT help
How could I nicely handle the first slider_change this receives? It's ran before the parent is fully constructed so it ends up with the initial tooltip label being placed somewhere at the top after being mapped to parent https://paste.fuelrats.com/neciroqaxu.py
If i place my frames using place layout manager then will i be able to place widgets on that frame?
When you use QLabel.setTextInteractionFlags(qtg.Qt.TextEditorInteraction) to make a label editable, is there any signals to connect when the editor is destroyed?
hey guys
in wxpython is this best way of creating a new window ? like you would new window for settings or something
best GUI Library for python?
simpliest to use... SimpleGUI, just the best to use PyQT6/PySide6 (the only drawback is complicated licensing situation, which makes big problem for commercial probjects)
ok
and GTK?
is it any good?
dunno. but it looks like having visual editors, which is already high plus in my opinion. License looks nice, not restrictive, docs look rich.
I would have tried it I guess
can anyone help me with on how i can use a button to open a text. i coded the button but i dont know how i can make it work like a button that opens something. in python btw
Any suggestions on improving this structure wise?
personally I would make the array of buttons on the bottom bar horizontal and wider so they are easier to click
Can I get constructive criticism on this
Its the first time I've attempted to add material design into my project :)
||waitt, am I using this channel correctly?||
import sys
from PyQt5 import QtCore, QtGui, QtWidgets,uic
class TestGUI(QtWidgets.QMainWindow):
def __init__(self):
super(TestGUI, self).__init__()
self.myui = uic.loadUi('SPTMain.ui', self)
self.NewTab.clicked.connect(self.handleAddTab)
def handleAddTab(self):
contents = QtWidgets.QWidget(self.myui)
layout = QtWidgets.QVBoxLayout(contents)
self.tabWidget.addTab(contents, 'Tab One')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = TestGUI()
window.show()
sys.exit(app.exec_())
Actually It adds blank tab... Kindly guide me how can I add new tab as my ui (duplicate of my .ui file in new tab)
where should I mention my qwidget (ui file) in new tab of qtabwidget so that it adds my ui...
What would be the proper way to add a button event to a tkinter button? Currently i have:
def fetch_login():
username = username_label_entry.get()
password = password_label_entry.get()
login.attempt_login(username, password)
login_button = ttk.Button(text="Log in!", style="Accent.TButton", command=fetch_login)
login_button.bind('<Return>', fetch_login)```
But it is throwing me an error: `TypeError: fetch_login() takes 0 positional arguments but 1 was given`
Do i need to create an additional function which would take keypress as an argument, and then execute the function i need or?
oo thanks
oo u mean the icons? yea they look nice, but the way your UI is layed out kind of makes it seem plain as a whole ngl
umm I don't think the binding is necessary here, try running is without the last line
Nothing happens on keypress then
But i noticed something weird even with binding
Enter wont work untill i click on button manually once
Just execute a function
So both Return key and mouse button on button should do same thing
hmm
so like it checks of any keypress?
I make my buttons like this, and they work fine
ill try using ur code
yea return doesnt work for me either
π€
uh, is there any way to have rich tables be the same width regardless of contents?
yes there is btw, min_width and max_width on Table.add_column
its supposed to be neat as a starting point. I don't wanna clutter it and make it hard for first time users
what exactly r u coding in? tkinter?
Yeah tkinter
Just specify "white"
bg='white'
On the label
tkinter discussions here right?
yep i think so
I'm using PySide2 and have a main app and a worker thread.
I was wondering how I can get the thread to safely trigger a function in the main class from the main thread.
I've been looking in to using QSlots and QSignals and things but I haven't found anything that works.
Any help is appreciated!
found a viable workaround, so it's all good now :)
idk this is raleted with this channel but what is wrong?
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
import time
class MyApp(App):
def build(self):
return Builder.load_string(
"""
Label:
font_size: 32"""
)
def on_start(self):
Clock.schedule_interval(
self.update, 1
)
def update(self, *args):
h = time.strftime("%H")
m = time.strftime("%M")
s = time.strftime("%S")
MyApp().run()
app is opening but there is just black a screen
it should show the time
Wow! You guys are way ahead of me!
you'd need to in some way to update a text attribute in that label
No i take them from a video i'm only learning rn
Hello, I was wondering how can I add a background in a ttk.notebook ?
I tried this but my bg isn't at the screen when I run the script
Ohh ok lol same here!
Idk what type of program you are making, but if it were me, I'd just use a frame in a tk window, it's much easier to play with
Then you can use bg to change it's colour
Btw why don't you send an ss of the output and also tell us if there are any error msgs you are getting
Well I just wanna get an UI with buttons and tabs with a background image
It doesn't get me an error msg
It just put a white bg instead of my image
Ohh like that you meant, then idk I haven't started using images yet... Sry
import tkinter as tk
from tkinter.filedialog import askopenfilename
import pandas as pd
def import_csv_data():
global v
csv_file_path = askopenfilename()
print(csv_file_path)
v.set(csv_file_path)
global df
df = pd.read_csv(csv_file_path)
print(df.head())
def showMean():
calcMeanNA = Button(root, text = "NA_Sales", command = calcMean("NA_Sales"))
calcMeanNA.grid(row = 4, column = 0)
calcMeanEU = Button(root, text = "EU_Sales", command = calcMean("EU_Sales"))
calcMeanEU.grid(row = 8, column = 0)
calcMeanJP = Button(root, text = "JP_Sales", command = calcMean("JP_Sales"))
calcMeanJP.grid(row = 12, column = 0)
calcMeanglb = Button(root, text = "Global_Sales", command = calcMean("Global_Sales"))
calcMeanglb.grid(row = 16, column = 0)
# resultLabel.config(text = "The Mean is: " + str(meanRes))
def calcMean(columna):
x = df[columna]
mean = x.mean()
# CalcmeanBtn = Button(root, text = column, command = showMean)
# CalcmeanBtn.grid(row = 4, column = 0)
resultLabel.config(text = "The Mean of "+ columna +" is: " + str(mean))
# def display():
root = tk.Tk()
root.geometry("500x500")
tk.Label(root, text = 'File Path').grid(row = 0, column = 0)
v = tk.StringVar()
entry = tk.Entry(root, textvariable = v).grid(row = 0, column = 1)
tk.Button(root, text = 'Browse Data Set', command = import_csv_data).grid(row = 1, column = 0)
meanBtn = Button(root, text = "Mean", command = showMean)
meanBtn.grid(row = 4, column = 0)
# num_list = df.select_dtypes(include = np.number).columns.tolist()
#
resultLabel = Label(root, text = "Result: -", font = (None, 10))
resultLabel.grid(row = 2, column = 0, columnspan = 3, sticky = "nwes", pady = 7)
tk.Button(root, text = 'Close', command = root.destroy).grid(row = 1, column = 1)
root.mainloop()
In this, when I run it and browse the file and click on mean, it shows me the mean of global sales only
Like what i wanted to do was When I click on the mean button the 4 columns would appear with button and when I click on them, the mean would be displayed of each..
Quick question, I'm trying to add an .ico image to a Tab (ttk.notebook). The code runs fine, but it doesn't show the .ico. Does anyone know what it's going wrong, please? Thanks
`from tkinter import *
from tkinter import ttk
import os
root = Tk()
icopath = os.getcwd() + '\Config\Icos\Bot.ico'
tab_control = ttk.Notebook(root)
tab_control.pack(expand=1, fill='both')
tab1 = ttk.Frame(tab_control)
tab_control.add(tab1, text='TAB TEXT', image = icopath, compound = LEFT, padding = 15)
root.mainloop()`
pls help me with this..
Hmm
Can you create a different help channel instead of posting it in an occupied one please
You you send me a screenshot of how the program works
The output I mean
Okay
Just after running the code
After browsing the file and clicking on mean button
Ok so what do you want to happen when it click mean?
it should display these 4 buttons..
And when I click on each of them it should display their mean
Like when I click on NA_Sales, it should display mean of NA_Sales, same for EU_Sales and others..
Ok
Right now what is happening is
When I click on mean button , automatically it is showing mean of global sales and the 4 buttons are not working
sure
So what you need to do is detect the output when the buttons are clicked like you did when you coded the detection of the "mean" button.
Then you need to calculate the mean fkr that, and display it in a label
Pack the calculated data and display it next to the buttons
But can't you just put the data into a label and display it without the hassle of detecting the event of a button?
I want to display the mean only when the button is clicked
Ok
Then follow this
What is wrong in this?
why only global sales mean is showing
I did not understood this..
What I need to do? in the code part?
I'm not sure
I barely have experience with tkinter I'm just going off knowledge that I know already
Sorry I couldn't help
no worries
i will try to do this
Thanks
You need to put in something to the tab1 frame in order to really show up. That's the same problem I had face when doing tabs
Does anyone know how you can change a ttk.Progressbar's background colour? I've searched everywhere and have only been able to change the actual progress part (that is usually green) to a different colour, rather than the real background. It looks really weird against the dark mode aesthetic I have in my program.
sorry dunno, but it looks really cool. I've tried using themes for my tkinter and it really slowed down.
Yeah I guess it's not too bad as it's a fairly small part of the program at the bottom. I suppose there isn't a way to do it as many of the Tkinter programs I've seen aren't "modern" in the sense that they have a dark mode anyway, so it may have just never been developed.
surely they are not taking good care for 'aesthetic' parts of it.
AH I figured it out! You've got to install a module called ttkthemes and then change ttk.Style() to ThemedStyle() and then you have access to all of these themes: https://wiki.tcl-lang.org/page/List+of+ttk+Themes
Tclers wiki
yes that works, I've almost tried all of them
but the 'app getting really slow' part made me abandon themes
some do slow the app while the others do not
Yeah. I think since the rest of my program is just using colour codes that I manually put in, the themes shouldn't slow too much, hopefully...
I think it has to do with nudging in 'svg' files in
your way won't affect the performance I guess
a little bit digressing, but check this out too.
https://github.com/rdbende/Azure-ttk-theme
looks neat, and it does not seem to slow down the program too.
That does actually look pretty useful. However I'm about 24 hours into banging my head against the wall trying to figure out colour codes so I'm just going to reserve this for another program I make rather than replacing all the stuff I did π
Yes that kind of work deserves a medal, don't let that go away
Just wanted to add that there is also ttk bootstrap which I have never used but have bookmarked for some while: https://github.com/israel-dryer/ttkbootstrap
thanks for the link. I would definitely try it on next design. it looks very good
Do people always use wildcard import from tkinter import * with tkinter?
I'm rather new to tkinter but I have been using "import tkinter as tk"
Yeah, I do that, too
If there are "x" number of columns in a database and I want to create "x" buttons and when I click on them it would show the mean of each
How to do that?
how do you get the number for the line in which the insertion cursor in the Text widget (Tkinter)?
i hate discord
INSERT
That's the thing
Oh the line
Yes-
line insert maybe?
Oh, with the index method
I'm pretty sure it exists let me check
There you go:
Text.index("insert linestart")
guys a small doubt, is there any difference between a 'class()' and a def function()'? if there is then can sm1 pls tell me the difference because i see many people use class() in their videos on yt but I don't see the need to...
I've simplified the code to post it here. I'm using buttons and entry boxes in the frame, but the .ico doesn't show it anyway π¦
Never did anything with a gui really, I want to make a sorting visualizer, can someone recommend me what to use please? preferably something I can use to later extend and do other algorithms too. Should I use tkinter?
Hey can anyone tell me how can i call multiple function using a for loop
What u wanna do
What u can do is that
func = [f1, f2, f3] for i in func: i()
I see no code. if you do post it I'll give it a try to find out what's the problem. I have a working tabs code. maybe I could compare it
classes are created to manage massive codes more easily. If your code is small and don't feel necessary to create one, you don't need to use them. If you are planning to create sth big, take time to look around what the class is.
thanks dude
With βtasksβ, would it be that i should create a task, that will run different functions on my UI for creating a note? I have a simple Pi Zero with a react UI, that Iβm running, and i have a button that i want to βset upβ a new note. Sooooo, is that where i run a βtaskβ that will cause automation to create the note when the button is pushed?
Does anyone have experience with Eel?
It tastes good
how can i make those buttons to the end
and if i try to resize the window with mouse
the button resize accordingly
i want to kee the width but want length is as the windows size
hi! how could i make something like this in python, if it even is possible?
yeap
they are on multiple lines and i think theyre updating asynchronously
@mild cedar
yeah well that is easy you need to so hard code on tracking all downloaded and total bytes
but how do i update multiple lines on the terminal at the same time?
i though you could only use \r for one line
wait
\n
no?
its the same line
yeah
eh
like
this is a code
for
loadbar
def progress_bar(seconds, prefix="[*] Waiting: "):
for i in range(seconds+1):
percent = 100.0 * i / seconds
sys.stdout.write('\r') # this is to clear the output ON the same line
sys.stdout.write(f"{prefix}[{'=' * int(percent / (100.0 / 30) ):{30}}] {int(percent):>3}%")
sys.stdout.flush()
sleep(1)
this prints
[*] Waiting: [================== ]
but that is just one line,
what i want to do is:
update multiple lines at the same time.
as you can see im using the \r to clear the line here, but that words just on this line,
how can i make it clear other lines
not sure the thing that you asked... but worth the try. it is from tkdocs tutorial
i tried everything nothing is working
hmm wierd. it says it should be working here
https://stackoverflow.com/questions/24644339/python-tkinter-resize-widgets-evenly-in-a-window
Hello im using pysimpleGUI and i have a window with a background and i want to add 2 pictures (they are flags so the user can choose language) so they can continue to another window with their language. anyone got a guide or knows approximately how to do that?
def main():
def test():
print(key.get())
if key.get() == "test":
lic.destroy()
Application().mainloop()
lic = tk.Tk()
tk.Label(lic, text="Enter Key"
).grid(row=0, column=0, pady=25, padx=15)
key = tk.Entry(lic)
key.grid(row=0, column=1, pady=25, padx=15)
tk.Button(lic, width=10, height=2, text="Submit", command=test
).grid(row=0, column=2, pady=25, padx=15)
lic.mainloop()
main()
can anyone do the same in better way
or likke in class inheritance
class Application(tk.Tk):
def __init__(self):
super().__init__()
here is my application class
i am trying to make a licence window
first pass the licence before open the main app window
rn its working as i want it to be
I'd expect react native to be faster considering its size and kivy being a wrapper around opengl that then needs to packaged for the platform
Guys, I have a doubt, how do we use the time import in tkinter, because whenever I try to use it, it never works!
you mean
import time
??
newsapp-abipravi.netlify.app how is my UI
no no ik how to import time, but when i try to use it in a code, for eg, some tkinter code, time.sleep(3), some other tkinter label to appear after 3 seconds, what happens is that the entire code gets paused for 3 seconds and then comes onto screen, but what i want to happen is that a label first appears when the code is run, and then afterwaiting for 3 seconds, a second label should appear, not all at once...i hope you understand what i am trying to tell you
Event Loop: Part of a Modern Tk Tutorial for Python, Tcl, Ruby, and Perl
In order to make things work without pausing the GUI you should understand how event loops work.
time.sleep(3)
This would definitely stop the GUI & entire application. Consider using this function
root.after(<time in ms>, <function>)
good luck
Using Eel, how do i set it to take full screen dimensions?
Is QT or Tkinter better to use for microcontrollers? Or, how about node?
made some improvements to the custom tkinter popup menus :)
and also i tried making a custom diff viewer
hey everyone,
can anyone please tell me how to customise title bar in tkinter
The window decoration is handled by the window manager, in order to customize your title bar you will have to remove all the decorations using .overrideredirect(), but you will also lose the default functionality of resizing, iconifying, or closing the window
in your case, simply call .overrideredirect(True) on root, and add your custom title bar object, that will do
i found one solution on internet but i cant understand one function in it
`from tkinter import *
from tkinter import font
root = Tk()
def move_window(event):
root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))
root.overrideredirect(True) # turns off title bar, geometry
root.geometry('400x100+200+200') # set new geometry
make a frame for the title bar
title_bar = Frame(root, bg='white', relief='raised', bd=2)
put a close button on the title bar
close_button = Button(title_bar, text='X', command=root.destroy)
a canvas for the main area of the window
window = Canvas(root, bg='black')
pack the widgets
title_bar.pack(expand=1, fill=X)
close_button.pack(side=RIGHT)
window.pack(expand=1, fill=BOTH)
Label(window, text='TEXT', font='Lucida 40 bold', fg='black').pack()
bind title bar motion to the move window function
title_bar.bind('<B1-Motion>', move_window)
root.mainloop()`
this move_window function
since you used overrideredirect your window will not be draggable with the mouse, this function tries to simulate the movement with the mouse
Do you have a tip to handle iconifying?
How should I iconify a window?
Just move it off the screen?
I also need an icon of an app appearing in the taskbar
you can use a treeview for that
or use a bunch of labels on a grid, that works too
see an example here
https://stackoverflow.com/questions/42748343/how-to-show-csv-file-in-a-grid
Stack Overflow
I'm trying to figure out how to display a .csv file in tkinter's grid, but haven't found much online.
Here is how far I got.
import tkinter
root = tkinter.Tk()
for r in range(3):
for c in r...
How do i change pygame application icon?
first load the image as a surface, the use pygame.display.set_icon()
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
this is so cool
hey guys
thank you :)
How do i remove/colour the outer while part of canvas
There is a white gap between canvas and bordee
Hello is it possible to for example, when the user clicks the button it will change pictures
so I know how to use pictures as buttons but how could i configre the button when its clicked to change to another image?
anyone?
Yes
U can put all images in list then u can iterate, them using index suck that the 'next' button will increase index value by one and then the image retreshes
How to display top 10 records from a csv file in tkinter?
Is it possible to change the colour of this flashing bar in entry widgets?
Oof, that image isn't great, you've got to look really close. If you can't see it, then it's the little bar that shows you where you are in the text when you click on it.
Nvm figured it out. It's this:
Entry(root, insertbackground="#FFFFFF")
is there anybody familiar with PyQt can tell me How can i use 2 QTimer in a single script?
Can't you just name 2 seperate variables as the two timers?
i tried, It crashes
I'm really far from an expert, but my guess is that when the first timer emits the signal and you have it do something, the second timer gets "stuck" because you may be doing everything in the main thread. Perhaps you could try doing the task for each timer in separate threads?
I also need some help in case someone can give me a hand. I've been at this for hours and I can't spot the mistake. I'm sorry for barging in @digital rose
π i can't be a much help in this problem, i am not familiar with those
@digital rose what was the error message?
simply assign an image changing function to your button
for example ```py
def change_icon():
btn.config(image=another_image)
btn = tk.Button(parent, image=first_image, command=change_icon)
Stack Overflow
I'm trying to figure out how to display a .csv file in tkinter's grid, but haven't found much online.
Here is how far I got.
import tkinter
root = tkinter.Tk()
for r in range(3):
for c in r...
Configure your canvas to have highlightthickness=0.
The Canvas has two components that affect the edges: the border (borderwidth/bd attribute) and highlight ring (highlightthickness attribute).
settings highlightthickness=0 during the instantiation may not help, you will have to use .config()/.configure() method
the idea of creating a custom treeview that can hold more than just labels is getting interesting
I liked your work so much it seems like another level, can u give me some hints that how do u do this
Using tcl?
oh no, its all just tkinter, some widgets fail to help me achieve what i need, so goes making my own ones :)
@indigo crane there is still a poxel space on right and bottom
I filled hightlightcolour with same screen colour
Oops sry for a ping, i just pinged u without thinking myself firstπ
ty
Does anyone have like any starting code if I want to make different pages and in differnet files?
might be the relief
try these bd=0, highlightthickness=0, relief='ridge'
that works too :)
pages? like different windows? maybe you are looking for Toplevel windows
Like
we can use different classes
I saw this off somewhere
class Page2(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Page 2", font=LARGEFONT)
label.grid(row=0, column=4, padx=10, pady=10)
# button to show frame 2 with text
# layout2
button1 = ttk.Button(self, text="Page 1",
command=lambda: controller.show_frame(new_main_flixgen.Page1))
# putting the button in its place by
# using grid
button1.grid(row=1, column=1, padx=10, pady=10)
# button to show frame 3 with text
# layout3
button2 = ttk.Button(self, text="Startpage",
command=lambda: controller.show_frame(new_main_flixgen.StartPage))
# putting the button in its place by
# using grid
button2.grid(row=2, column=1, padx=10, pady=10)
But I want the classes to be in different files
coz I'm planning on having alot of code and it wont all fit