AttributeError: 'users_Arduino' object has no attribute 'Progressbar' - python-3.x

I have tried in several ways, set it with ttk.Progressbar, with self.progresso.Progressbar ... and nothing, anyone can help? I'm still young then sorry for ignorance. If they can be as clear as possible, thank you.
from tkinter import *
from tkinter import ttk
import time
class users_Arduino:
def __init__(self,window):
self.wind = window
self.wind.title("System F2T - Cadastro Arduino")
menubar = Menu(window)
arduino = Menu(menubar,tearoff=0)
menubar.add_cascade(label = "Arduino",menu=arduino)
arduino.add_command(label = "Conectar/Inserir dados-BD", command=self.getSerialData)
window.config(menu = menubar)
def bar():
progress['value'] = 20
root.update_idletasks()
time.sleep(1)
progress['value'] = 40
root.update_idletasks()
time.sleep(1)
progress['value'] = 50
root.update_idletasks()
time.sleep(1)
progress['value'] = 60
root.update_idletasks()
time.sleep(1)
progress['value'] = 80
root.update_idletasks()
time.sleep(1)
progress['value'] = 100
def getSerialData(self):
self.progresso = Toplevel()
self.progresso.title("System F2T - Progress")
self.progresso.geometry("290x200")
#self.progresso["bg"] = "#000"
progress = self.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate').pack(pady = 10)
Button(self.progresso, text = 'Start', command = self.bar).pack(pady = 10)
if __name__ == '__main__':
window = Tk()
window['bg'] = "#000"
users_Arduino(window)
window.mainloop()

You are trying to access a class attribute by using self.Progressbar, which obviously won't work. What you intended is to create a Progressbar, which should be done like below:
progress = ttk.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate').pack(pady = 10)
Next, you wanted the Progressbar to update every second until it reaches 100, but calling time.sleep will block your main thread and freeze your GUI. You need to use root.after method.
Also if you call something=widget(...).pack() at the same line, you are not keeping a proper reference of the object. The return value will just be None.
So everything wrapped up:
from tkinter import *
from tkinter import ttk
class UsersArduino:
def __init__(self,window):
self.wind = window
self.wind.title("System F2T - Cadastro Arduino")
self.value = 0
menubar = Menu(window)
arduino = Menu(menubar,tearoff=0)
menubar.add_cascade(label = "Arduino",menu=arduino)
arduino.add_command(label = "Conectar/Inserir dados-BD", command=self.getSerialData)
window.config(menu = menubar)
def bar(self):
self.progress['value'] +=20
if self.progress['value'] <=100:
self.wind.after(1000,self.bar)
def getSerialData(self):
self.progresso = Toplevel()
self.progresso.title("System F2T - Progress")
self.progresso.geometry("290x200")
self.progress = ttk.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate')
self.progress.pack(pady = 10)
Button(self.progresso, text = 'Start', command = self.bar).pack(pady = 10)
if __name__ == '__main__':
window = Tk()
window['bg'] = "#000"
UsersArduino(window)
window.mainloop()

Related

tkinter e Adafruit IO Why the cycle while it is not working?

I've recently been using python....
I cannot understand why the while loop prevents the creation of the tkinter window.
If I move the while loop before the mainloop I display the tkinter window but the loop stops.
import tkinter as tk
import time
from Adafruit_IO import Client, Feed, RequestError
ADAFRUIT_IO_USERNAME = "***********"
ADAFRUIT_IO_KEY = "**********************"
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
loop_delay = 5
temp = 25
try:
temperature = aio.feeds('temperature')
except RequestError:
feed = Feed(name="temperature")
temperature = aio.create_feed(feed)
def sendtemp(temp):
aio.send_data(temperature.key,temp)
data = aio.receive(temperature.key)
print(data.value)
window = tk.Tk()
window.title ("Thermometer")
window.geometry("300x100")
label = tk.Label(window, text = temp)
label.pack()
window.mainloop
while True:
sendtemp(temp)
time.sleep(loop_delay)
I solved it this way, what do you think?
import tkinter as tk
from Adafruit_IO import Client, Feed, RequestError
ADAFRUIT_IO_USERNAME = "**********"
ADAFRUIT_IO_KEY = "***************"
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
try:
temperature = aio.feeds('temperature')
except RequestError:
feed = Feed(name="temperature")
temperature = aio.create_feed(feed)
class Timer:
def __init__(self, parent):
self.temp = 25
self.label = tk.Label(text="--,- °C", font="Arial 30", width=10)
self.label.pack()
self.label.after(5000, self.sendtemp)
def sendtemp(self):
aio.send_data(temperature.key,self.temp)
data = aio.receive(temperature.key)
print(data.value)
self.label.configure(text="%i°C" % self.temp)
self.temp +=1
self.label.after(5000, self.sendtemp)
if __name__ == "__main__":
window = tk.Tk()
window.title ("Thermometer")
window.geometry("300x100")
timer = Timer(window)
window.mainloop()
Your while loop is blocking the program. It literally does nothing but calling sendtemp and sleeping.
while True:
sendtemp(temp)
time.sleep(loop_delay)
There is no room for reacting to events on the TK window, Python is busy doing those two things.
To do actions periodically, you need to set up a timer that runs on TK's main event loop (the one you start with .mainloop()). This is done with the .after() method.
This method takes a millisecond delay and a function you want to call.
window = tk.Tk()
window.title ("Thermometer")
window.geometry("300x100")
timer_id = None
timer_delay = 5000
def sendtemp(temp):
aio.send_data(temperature.key,temp)
data = aio.receive(temperature.key)
print(data.value)
if timer_id is not None:
start_timer()
def start_timer():
global timer_id
timer_id = window.after(timer_delay, sendtemp)
def stop_timer():
global timer_id
if timer_id is not None:
window.after_cancel(timer_id)
timer_id = None
start_timer()
window.mainloop()
You could bind stopping and starting the timer to a button.

Gif animation with tkinter and classes in Python 3

I'm having some problems making my gif work in this code.
its a kind of media player with a graphic equalizer :)
I'm trying to make gif play inside the "pantalla" label. I'm having an attribute error with the frame variable. I've been looking around but cannot solve the problem.
sorry for my mistakes I'm a newbie.
any help will be appreciated.
here the code:
import os
from tkinter import *
from vlc import Instance
import time
app = Tk()
app.title("JlMultimedia")
app.iconbitmap("C:/Users/Thunder/Documents/Projects/Python/auricular.ico")
app.geometry("340x250")
app.config(bg="blue")
frames = [PhotoImage(file='C:/Users/Thunder/Documents/Projects/Python/imagenes/equalizer1.gif', format = 'gif -index %i' %(i)) for i in range(5)]
def update(self, ind):
self.frame = frames[ind]
ind += 1
print(ind)
if ind>4: #With this condition it will play gif infinitely
ind = 0
app.after(100, update, ind)
class Jlmultimedia:
def __init__(self):
self.Player = Instance('--loop')
capa = Frame(app)
capa.config(bg="#ffffff")
capa.pack(expand="1")
capa1 = Frame(capa, bg="#0000ff")
capa1.config()
capa1.pack(expand="1")
pantalla = Label(capa1, image=self.frame)
pantalla.grid(row="0", columnspan="3")
self.playimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/play4.png")
self.stopimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/stop4.png")
self.pauseimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/pause4.png")
self.nextimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/forw4.png")
self.backimage = PhotoImage(file="C:/Users/Thunder/Documents/Projects/Python/imagenes/rew4.png")
capa2 = LabelFrame(capa)
capa2.config(bg="#ffffff")
capa2.pack(expand="1")
playboton = Button(capa2, image=self.playimage, bd="0", command=self.play)
playboton.grid(row="1", column="1")
self.volVar = IntVar()
volboton = Scale(capa2, from_=100, to=0, resolution=1, length=90,
label="Vol", variable=self.volVar, command=self.set_volume)
volboton.grid(row="1", column="6")
stopboton = Button(capa2, image=self.stopimage, bd="0", command=self.stop)
stopboton.grid(row="1", column="2")
pauseboton = Button(capa2, image=self.pauseimage, bd="0", command=self.pause)
pauseboton.grid(row="1", column="4")
nextboton = Button(capa2, image=self.nextimage, bd="0", command=self.next)
nextboton.grid(row="1", column="3")
preboton = Button(capa2, image=self.backimage, bd="0", command=self.previous)
preboton.grid(row="1", column="5")
# panel to hold player time slider
self.timeVar = DoubleVar()
self.timeSliderLast = 0
self.timeSlider = Scale(capa1, variable=self.timeVar, command=self.OnTime,
from_=0, to=1000, orient=HORIZONTAL, length=328, showvalue=0) # label='Time',
#self.timeSlider.pack(side=BOTTOM, fill=X, expand=1)
self.timeSliderUpdate = time.time()
self.timeSlider.grid(row="1", columnspan="5")
def addPlaylist(self):
self.mediaList = self.Player.media_list_new()
path = r"C:/Users/Thunder/Documents/Projects/Python/musica"
songs = os.listdir(path)
for s in songs:
self.mediaList.add_media(self.Player.media_new(os.path.join(path,s)))
self.listPlayer = self.Player.media_list_player_new()
self.listPlayer.set_media_list(self.mediaList)
def set_volume(self, *unuse):
vol = min(self.volVar.get(), 100)
self.listPlayer.get_media_player().audio_set_volume(vol)
def play(self):
self.listPlayer.play()
def next(self):
self.listPlayer.next()
def pause(self):
self.listPlayer.pause()
def previous(self):
self.listPlayer.previous()
def stop(self):
self.listPlayer.stop()
def OnTime(self, *unused):
if self.listPlayer:
t = self.timeVar.get()
if self.timeSliderLast != int(t):
self.listPlayer.get_media_player().set_time(int(t * 1e3)) # milliseconds
self.timeSliderUpdate = time.time()
myPlayer = Jlmultimedia()
myPlayer.addPlaylist()
app = mainloop()
There are several issues:
update() has never been executed
image option of label pantalla should be update as well inside update()
pantalla is a local variable inside Jlmultimedia.__init__(), you should make it instance variable self.pantalla
self.frame is undefined
app = mainloop() should be app.mainloop()
Below is a modified update():
def update(ind=0):
myPlayer.pantalla.config(image=frames[ind%len(frames)])
app.after(100, update, ind+1)
And changing pantalla to instance variable inside __init__():
class Jlmultimedia:
def __init__(self):
...
self.pantalla = Label(capa1)
self.pantalla(row=0, columnspan=3)
...
Then call update() before app.mainloop():
...
update()
app.mainloop()

how can i control each button individually in tkinter

How can i control each button individually in tkinter?
Here is my code:
from tkinter import *
class Minesweeper:
def __init__(self,action):
L=[]
for i in range(15):
for j in range(15):
self.action = Button(win, text = " h ",command = self.clickMe)
self.action.grid(column = i, row = j)
def clickMe(self):
self.action.configure(foreground = "red")
def main():
global win
win = Tk()
win.title('Minesweeper')
game = Minesweeper(win)
win.mainloop()
main()
Better way is a binding some event to button:
from tkinter import *
class Minesweeper:
def __init__(self, action):
L=[]
for i in range(15):
for j in range(15):
self.action = Button(win, text="h")
# bind to button function 'clickMe' that runs while <Button-1> clicked on it
self.action.bind("<Button-1>", self.clickMe)
self.action.grid(column=i, row=j)
def clickMe(self, event):
"""changes the 'fg' color of the events widget"""
event.widget.configure(foreground="red")
def main():
global win
win = Tk()
win.title('Minesweeper')
game = Minesweeper(win)
win.mainloop()
main()

updating python3 tkinter label not working

I can manually update label and entry if i clicked the manual button, but if i clicked the auto button... the console show the random number but the widgets are not updating.
from tkinter import *
import random
import time
def manual_settxt():
for t in range(0,3):
rd = random.randrange(1,100)
labelWidgets[t].configure(text=rd)
entryWidgets[t].delete(0,END)
entryWidgets[t].insert(0,rd)
def auto_settxt():
while True:
time.sleep(3)
for t in range(0,3):
rd = random.randrange(1,100)
print(rd)
labelWidgets[t].configure(text=rd)
entryWidgets[t].delete(0,END)
entryWidgets[t].insert(0,rd)
root = Tk()
namesInput = [1,2,3]
entryWidgets = []
labelWidgets = []
for i in range(0, len(namesInput)):
labelWidgets.append(Label(root,text=namesInput[i],justify='center'))
entryWidgets.append(Entry(root,width=5,justify='center'))
labelWidgets[-1].grid(row=i+1,column=0)
entryWidgets[-1].grid(row=i+1,column=1)
b1 = Button(root, text = "Manual", command=manual_settxt)
b1.grid(row=4,column=0)
b2 = Button(root, text = "Auto", command=auto_settxt)
b2.grid(row=4,column=1)
root.mainloop()
You created an infinite loop. Delete while True.
I refactored some code: used Thread for non-blocking functionality.
Try this
from tkinter import *
import random
import time
from threading import Thread
def manual_settxt():
for index in range(3):
rd = random.randrange(1,100)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
def job():
for index in range(3):
time.sleep(1)
rd = random.randrange(1,100)
print(rd)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
def auto_settxt():
Thread(target=job).start()
root = Tk()
namesInput = [1,2,3]
entryWidgets = []
labelWidgets = []
for index, name in enumerate(namesInput):
labelWidgets.append(Label(root, text=name, justify='center'))
entryWidgets.append(Entry(root, width=5, justify='center'))
labelWidgets[-1].grid(row=index+1,column=0)
entryWidgets[-1].grid(row=index+1,column=1)
b1 = Button(root, text = "Manual", command=manual_settxt)
b1.grid(row=4,column=0)
b2 = Button(root, text = "Auto", command=auto_settxt)
b2.grid(row=4,column=1)
root.mainloop()
I use "root.after" and the script seems to be working fine.
from tkinter import *
import random
import time
def manual_settxt():
for index in range(3):
rd = random.randrange(1,100)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
def auto_settxt():
for index in range(3):
rd = random.randrange(1,100)
print(rd)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
root.after(1000, auto_settxt)
root = Tk()
namesInput = [1,2,3]
entryWidgets = []
labelWidgets = []
for index, name in enumerate(namesInput):
labelWidgets.append(Label(root, text=name, justify='center'))
entryWidgets.append(Entry(root, width=5, justify='center'))
labelWidgets[-1].grid(row=index+1,column=0)
entryWidgets[-1].grid(row=index+1,column=1)
b1 = Button(root, text = "Manual", command=manual_settxt)
b1.grid(row=4,column=0)
b2 = Button(root, text = "Auto", command=auto_settxt)
b2.grid(row=4,column=1)
root.after(1000, auto_settxt)
root.mainloop()

Error: Attribute error in TCL

I am trying to create an application in Python GUI using tkinter. Here is the code I'm using for the GUI part. Whenever I try to access my Entry Widget I get error.
Ex:Sin_put.get() should give me the text in the Entry widget but it gives me an error
AttributeError: 'NoneType' object has no attribute 'get'
I'm relatively new to Python. So if you guys have any suggestions to improve the functionality you're most welcome.
from tkinter import *
from tkinter import ttk
sys.path.insert(0, 'home/ashwin/')
import portscanner
class App:
def __init__(self, master):
master.option_add('*tearOff', False)
master.resizable(False,False)
self.nb = ttk.Notebook(master)
self.nb.pack()
self.nb.config(width=720,height=480)
self.zipframe = ttk.Frame(self.nb)
self.scanframe = ttk.Frame(self.nb)
self.botframe = ttk.Frame(self.nb)
self.mb = Menu(master)
master.config(menu = self.mb)
file = Menu(self.mb)
info = Menu(self.mb)
self.mb.add_cascade(menu = file, label = 'Tools')
self.mb.add_cascade(menu = info, label = 'Help')
file.add_command(label='Zip Cracker', command = self.zipframe_create)
file.add_command(label='Port Scanner', command = self.scanframe_create)
file.add_command(label='Bot net', command =self.botframe_create)
info.add_command(label='Usage', command=(lambda:print('Usage')))
info.add_command(label='About', command=(lambda:print('About')))
def zipframe_create(self):
self.nb.add(self.zipframe,text='Zip')
self.zipframe.config(height=480,width=720)
zlabel1 = ttk.Label(self.zipframe, text='Select the zip file').grid(row=0,column=0, padx=5, pady=10)
zlabel2 = ttk.Label(self.zipframe, text='Select the dictionary file').grid(row=2,column=0, padx=5)
ztext1 = ttk.Entry(self.zipframe, width = 50).grid(row=0,column=1,padx=5,pady=10)
ztext2 = ttk.Entry(self.zipframe, width = 50).grid(row=2,column=1,padx=5)
zoutput = Text(self.zipframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
zb1 = ttk.Button(self.zipframe, text='Crack', width=10).grid(row=0,column=2,padx=5,pady=10)
def scanframe_create(self):
self.nb.add(self.scanframe,text='Scan')
self.scanframe.config(height=480,width=720)
slabel1 = ttk.Label(self.scanframe, text='IP address').grid(row=0,column=0, padx=5, pady=10)
sin_put = ttk.Entry(self.scanframe, width = 50).grid(row=0,column=1,padx=5,pady=10)
soutput = Text(self.scanframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
sb1 = ttk.Button(self.scanframe, text='Scan', width=6,command= print('Content: {}'.format(sin_put.get()))).grid(row=0,column=2,padx=5,pady=10)
def botframe_create(self):
self.nb.add(self.botframe,text='Bot')
self.botframe.config(height=480,width=720)
blabel1 = ttk.Label(self.botframe, text='IP address').grid(row=0,column=0, padx=5, pady=10)
blabel2 = ttk.Label(self.botframe, text='Username').grid(row=1,column=0, padx=2)
blabel3 = ttk.Label(self.botframe, text='password').grid(row=2,column=0, padx=2)
btext1 = ttk.Entry(self.botframe, width = 30).grid(row=0,column=1,padx=5,pady=10)
btext2 = ttk.Entry(self.botframe, width = 30).grid(row=1,column=1)
btext2 = ttk.Entry(self.botframe, width = 30).grid(row=2,column=1)
boutput = Text(self.botframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
bb1 = ttk.Button(self.botframe, text='Connect', width=8).grid(row=2,column=2,padx=5,pady=10)
def main():
root = Tk()
feedback = App(root)
root.mainloop()
if __name__ == "__main__": main()
grid() returns None so sin_put will always equal None. Instead of passing the Tkinter ID to grid() you have to store it first if you want to reference it later. Note that for the Buttons, putting it all on one line is fine as you don't use the button's ID later.
sin_put=ttk.Entry(self.scanframe, width = 50) ## stores the return ID from Entry
sin_put.grid(row=0,column=1,padx=5,pady=10) ## don't catch return from grid as it is None

Resources