I am creating a brightness toggle on Python. I am using the Tkinter module to create a sider function. I have successfully created a slider to increase/decrease the volume. However, I want to translate this into one where I can increase/decrease the screen's brightness. Here is my volume code and output.
I am currently using macOS Monterey Version 12.2.1.
#The GUI player
import pygame
from pygame import mixer
from tkinter import *
# Makes a new window and stores it inside the root variable.
root = Tk()
mixer.init() # initialising the mixer
# Coding the background music
def play_music():
pygame.mixer.music.load("ArcadeMusic copy.mp3")
pygame.mixer.music.play(-1)
def set_vol(val):
volume = int(val) / 100
mixer.music.set_volume(volume)
root.geometry('300x70')
root.title("Volume")
text = Label(root, text = "Drag the slider to adjust volume")
text.pack()
scale = Scale(root,from_=0,to=100 , orient=HORIZONTAL, command=set_vol)
scale.pack()
play_music()
root.mainloop()
Are you trying to achieve something like this? Or do you want to control desktop brightness?
import tkinter
def find( obj ):
name = f"{type(obj).__name__}:n "
try:
return name + "n ".join( [ f"{x} = '{obj.cget(x)}'" for x in obj.keys() ] )
except:
return f"'{obj}' has no keys attribute"
class brightness:
def __init__( self ):
self.master = tkinter.Tk()
self.master.update_idletasks()
self.color = 15790320 # #f0f0f0 = SystemButtonFace
self.var = tkinter.IntVar( self.master, value = self.color )
self.flexx( self.master )
self.label = tkinter.LabelFrame(
self.master, labelanchor = 'n', text = self.master['background'] )
self.label.grid( row=0, column=0, columnspan=2, sticky='nsew' )
self.flexx( self.label, r=None )
self.flexx( self.label, r=None , c=1 )
self.scroll = tkinter.Scale(
self.label, orient = 'horizontal',
resolution = 65793, label = 'Brightness Control',
from_ = 0, to = 16777215, variable = self.var,
command = self.control )
self.scroll.grid( row = 1, column=0, columnspan=2, sticky='ew' )
self.master.geometry( '200x200' )
self.master.minsize( 334, 113 )
def flexx( self, o, r = 0, c = 0, rw = 1, cw = 1 ):
if r != None:
o.rowconfigure( r, weight = rw )
if c != None:
o.columnconfigure( c, weight = cw )
def convert( self ):
col = '#' + ( '000000' + hex( self.color )[2:])[~5:]
self.var.set( self.color )
self.label['text'] = col
self.master.tk_setPalette( col )
def control_up( self ):
self.color += 65793
if self.color > 16777215:
self.color = 15790320
col = self.convert( )
def control_down( self ):
self.color -= 65793
if self.color < 0: # 15790320:
self.color = 16777215
col = self.convert( )
def control( self, n ):
self.color = int( n )
col = self.convert( )
if __name__ == '__main__':
bright = brightness( )
tkinter.mainloop()
Related
I am programming a minesweeper and I am stuck because I still have to add a timer. I was able to program one but I can only see it in my console. But i want it to be in my game so that someone who is playong can see the time.
Now how do I add my programmed timer to the game? Down here is my code the first one is for the cell with all the definitions the second one is the main part and the last part is my time. I still have two files called settings and utils but these aren‘t important for the problem…
from tkinter import Button, Label
import random
import settings
import ctypes
import sys
import time
import elapsed
class Cell:
all = []
cell_count = settings.CELL_COUNT
cell_count_label_object = None
def __init__(self,x, y, is_mine=False):
self.is_mine = is_mine
self.is_opened = False
self.is_mine_candidate = False
self.cell_btn_object = False
self.x = x
self.y = y
self.done = False
# Append the object to the Cell.all list
Cell.all.append(self)
def create_btn_object(self, location):
btn = Button(
location,
width=10,
height=3,
)
btn.bind('<Button-1>', self.left_click_actions ) # Left Click
btn.bind('<Button-3>', self.right_click_actions ) # Right Click
self.cell_btn_object = btn
#staticmethod
def create_cell_count_label(location):
lbl = Label(
location,
bg='aquamarine3',
fg='white',
text=f"Cells Left:{Cell.cell_count}",
font=("", 30)
)
Cell.cell_count_label_object = lbl
def left_click_actions(self, event):
if self.is_mine:
self.show_mine()
else:
if self.surrounded_cells_mines_length == 0:
for cell_obj in self.surrounded_cells:
cell_obj.show_cell()
self.show_cell()
# If Mines count is equal to the cells left count, player won
if Cell.cell_count == settings.MINES_COUNT:
ctypes.windll.user32.MessageBoxW(0, 'Congratulations! You won the game!', 'Game Over', 0)
# Cancel Left and Right click events if cell is already opened:
self.cell_btn_object.unbind('<Button-1>')
self.cell_btn_object.unbind('<Button-3>')
def get_cell_by_axis(self, x,y):
# Return a cell object based on the value of x,y
for cell in Cell.all:
if cell.x == x and cell.y == y:
return cell
#property
def surrounded_cells(self):
cells = [
self.get_cell_by_axis(self.x - 1, self.y -1),
self.get_cell_by_axis(self.x - 1, self.y),
self.get_cell_by_axis(self.x - 1, self.y + 1),
self.get_cell_by_axis(self.x, self.y - 1),
self.get_cell_by_axis(self.x + 1, self.y - 1),
self.get_cell_by_axis(self.x + 1, self.y),
self.get_cell_by_axis(self.x + 1, self.y + 1),
self.get_cell_by_axis(self.x, self.y + 1)
]
cells = [cell for cell in cells if cell is not None]
return cells
#property
def surrounded_cells_mines_length(self):
counter = 0
for cell in self.surrounded_cells:
if cell.is_mine:
counter += 1
return counter
def show_cell(self):
if not self.is_opened:
Cell.cell_count -= 1
self.cell_btn_object.configure(text=self.surrounded_cells_mines_length)
# Replace the text of cell count label with the newer count
if Cell.cell_count_label_object:
Cell.cell_count_label_object.configure(
text=f"Cells Left:{Cell.cell_count}"
)
# If this was a mine candidate, then for safety, we should
# configure the background color to SystemButtonFace
self.cell_btn_object.configure(
bg='SystemButtonFace'
)
# Mark the cell as opened (Use is as the last line of this method)
self.is_opened = True
def show_mine(self):
self.cell_btn_object.configure(bg='red')
ctypes.windll.user32.MessageBoxW(0, 'You clicked on a mine', 'Game Over', 0)
sys.exit()
def right_click_actions(self, event):
if not self.is_mine_candidate:
self.cell_btn_object.configure(
text = '🌸',
fg = 'red'
)
self.is_mine_candidate = True
else:
self.cell_btn_object.configure(
bg='SystemButtonFace'
)
self.is_mine_candidate = False
def time():
start_time = time.time()
while True:
if not self.is_opened:
elapsed_time = time.time() - start_time
print(int(elapsed_time))
#staticmethod
def randomize_mines():
picked_cells = random.sample(
Cell.all, settings.MINES_COUNT
)
for picked_cell in picked_cells:
picked_cell.is_mine = True
def __repr__(self):
return f"Cell({self.x}, {self.y})"
from tkinter import *
from cell import Cell
import settings
import utils
import elapsed
import time
root = Tk()
# Override the settings of the window
root.configure(bg="aquamarine3")
root.geometry(f'{settings.WIDTH}x{settings.HEIGHT}')
root.title("Minesweeper Game")
root.resizable(False, False)
top_frame = Frame(
root,
bg='aquamarine3',
width=settings.WIDTH,
height=utils.height_prct(15)
)
top_frame.place(x=0, y=0)
game_title = Label(
top_frame,
bg='aquamarine3',
fg='white',
text='Minesweeper Game',
font=('', 48)
)
game_title.place(
x=utils.width_prct(30), y=0
)
left_frame = Frame(
root,
bg='aquamarine3',
width=utils.width_prct(75),
height=utils.height_prct(75)
)
left_frame.place(x=0, y=utils.height_prct(25))
timer_title = Label(
left_frame,
bg = 'aquamarine3',
fg = 'white',
text = ('time:', command = cell.time)
)
timer_title.place(
x = 0, y = 100
)
center_frame = Frame(
root,
bg='aquamarine3',
width=utils.width_prct(75),
height=utils.height_prct(75)
)
center_frame.place(
x=utils.width_prct(25),
y=utils.height_prct(15),
)
for x in range(settings.GRID_SIZE):
for y in range(settings.GRID_SIZE):
c = Cell(x, y)
c.create_btn_object(center_frame)
c.cell_btn_object.grid(
column=x, row=y
)
# Call the label from the Cell class
Cell.create_cell_count_label(left_frame)
Cell.cell_count_label_object.place(
x=0, y=0
)
Cell.randomize_mines()
# Run the window
root.mainloop()
import time
time.gmtime(0)
start_time = time.time()
def timer():
while True:
elapsed_time = time.time()-start_time
print(int(elapsed_time))
I have a program written in Python, that makes a window where you can draw, using Tkinter. Every time you left-click your mouse, you make a point in your canvas. When you double-click, a polygon is made, filled with the color you chose. I found a way to change the colors from the boxes, when you right-click a box, but the problem is that the selected color is not saved and i cannot make it replace the previous one. Does anyone know how to solve this problem?
import tkinter as tk
from tkinter import colorchooser
class Point():
def __init__(self, canvas, x, y):
self.x = x
self.y = y
canvas.create_oval(x-2, y-2, x+2, y+2, fill='white')
class Poly():
def __init__(self, canvas, board, p_list=[] ):
self.p_list = p_list
self.canvas = canvas
self.board = board
def draw_poly(self):
points = []
for p in self.p_list:
points.extend([p.x, p.y])
points.extend(points[:2])
self.canvas.create_polygon(points, fill=self.board.current_color, outline=self.board.current_color)
def add_point(self, p):
self.p_list.append(p)
if len(self.p_list)>1:
p1 = self.p_list[-1]
p2 = self.p_list[-2]
self.canvas.create_line(p1.x, p1.y, p2.x, p2.y, fill="white", width=2)
class Palette():
def __init__(self, frame, board, colors):
self.colors = colors
self.board = board
self.allColors = []
for color in self.colors:
f = tk.Frame(frame, bg='lightgrey', bd=3)
f.pack(expand=1, fill='both', side='left')
if self.board.current_color == color: f.config(bg='red')
self.allColors.append(f)
l = tk.Label(f, bg=color)
l.pack(expand=1, fill='both', padx=2, pady=2)
l.bind("<1>", self.set_color)
l.bind("<Button-3>", self.do_popup)
def do_popup(self, event):
clsheet = tk.colorchooser.askcolor()
self.current_color = clsheet[1]
def set_color(self, e):
self.board.current_color = e.widget['bg']
self.selected_color(e.widget.master)
def selected_color(self, colorFrame):
for f in self.allColors: f.config(bg = 'lightgrey')
colorFrame.config(bg="red")
class Board():
def __init__(self, root):
self.colors = ['#B4FE98', '#77E4D4', '#F4EEA9', '#F0BB62', '#FF5F7E', "#9A0680"]
self.root = root
self.current_color = self.colors[0]
self.f1 = tk.Frame(self.root)
self.f1.pack(expand=1, fill='both', padx=5)
self.f2 = tk.Frame(self.root)
self.f2.pack(expand=1, fill='both')
self.canvas = tk.Canvas(self.f2, bg="#000D6B", height=550)
self.canvas.pack(expand=1, fill='both', padx=5, pady=5)
self.pallette = Palette(self.f1, self, self.colors )
self.canvas.bind("<1>", self.draw_point)
self.canvas.bind("<Double-Button-1>", self.draw_poly)
self.poly = None
def draw_point(self, evnt):
if self.poly: self.poly.add_point(Point(self.canvas, evnt.x, evnt.y))
else: self.poly = Poly(self.canvas, self, [Point(self.canvas, evnt.x, evnt.y)])
def draw_poly(self, evnt):
if self.poly and len(self.poly.p_list) > 2:
self.poly.add_point(Point(self.canvas, evnt.x, evnt.y))
self.poly.draw_poly()
self.poly = None
else: self.draw_point(evnt)
#main program
root = tk.Tk()
root.title('my program')
root.geometry("600x700")
root.resizable(0,0)
Board(root)
tk.mainloop()
To fix the part where right-clicking a color was not working i changed two things in your script:
You stored your frame widgets and their sub-widget labels in Palette.allColors. I handed over the index of the selected color to the do_popup event by using partial. Then you can simply iterate over all widgets in Palette.allColors and if the index from the event matches the index in the list, you access the children and further the !label key of those and change the background color to the selected color.
I matched Board.current_color and Palette.current_color
Most changes were made in Palette.do_popup(). Might not be the most elegant solution but it looks like its working like you intend. Full code:
import tkinter as tk
from tkinter import colorchooser
from functools import partial
class Point():
def __init__(self, canvas, x, y):
self.x = x
self.y = y
canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white')
class Poly():
def __init__(self, canvas, board, p_list=[]):
self.p_list = p_list
self.canvas = canvas
self.board = board
def draw_poly(self):
points = []
for p in self.p_list:
points.extend([p.x, p.y])
points.extend(points[:2])
self.canvas.create_polygon(points, fill=self.board.current_color, outline=self.board.current_color)
def add_point(self, p):
self.p_list.append(p)
if len(self.p_list) > 1:
p1 = self.p_list[-1]
p2 = self.p_list[-2]
self.canvas.create_line(p1.x, p1.y, p2.x, p2.y, fill="white", width=2)
class Palette():
def __init__(self, frame, board, colors):
self.colors = colors
self.board = board
self.allColors = []
for idx, color in enumerate(self.colors):
f = tk.Frame(frame, bg='lightgrey', bd=3)
f.pack(expand=1, fill='both', side='left')
if self.board.current_color == color: f.config(bg='red')
self.allColors.append(f)
l = tk.Label(f, bg=color)
l.pack(expand=1, fill='both', padx=2, pady=2)
l.bind("<1>", self.set_color)
l.bind("<Button-3>", partial(self.do_popup, idx))
def do_popup(self, idx, event):
clsheet = tk.colorchooser.askcolor()
self.current_color = clsheet[1].upper()
print(f"You chose: {self.current_color}")
self.board.current_color = self.current_color # required?
self.selected_color(event.widget.master)
for frm_idx, frm in enumerate(self.allColors):
if frm_idx == idx:
frm.children["!label"].config(bg=self.current_color)
def set_color(self, e):
self.board.current_color = e.widget['bg']
self.selected_color(e.widget.master)
def selected_color(self, colorFrame):
for f in self.allColors: f.config(bg='lightgrey')
colorFrame.config(bg="red")
class Board():
def __init__(self, root):
self.colors = ['#B4FE98', '#77E4D4', '#F4EEA9', '#F0BB62', '#FF5F7E', "#9A0680"]
self.root = root
self.current_color = self.colors[0]
self.f1 = tk.Frame(self.root)
self.f1.pack(expand=1, fill='both', padx=5)
self.f2 = tk.Frame(self.root)
self.f2.pack(expand=1, fill='both')
self.canvas = tk.Canvas(self.f2, bg="#000D6B", height=550)
self.canvas.pack(expand=1, fill='both', padx=5, pady=5)
self.pallette = Palette(self.f1, self, self.colors)
self.canvas.bind("<1>", self.draw_point)
self.canvas.bind("<Double-Button-1>", self.draw_poly)
self.poly = None
def draw_point(self, evnt):
if self.poly:
self.poly.add_point(Point(self.canvas, evnt.x, evnt.y))
else:
self.poly = Poly(self.canvas, self, [Point(self.canvas, evnt.x, evnt.y)])
def draw_poly(self, evnt):
if self.poly and len(self.poly.p_list) > 2:
self.poly.add_point(Point(self.canvas, evnt.x, evnt.y))
self.poly.draw_poly()
self.poly = None
else:
self.draw_point(evnt)
# main program
root = tk.Tk()
root.title('my program')
root.geometry("600x700")
root.resizable(0, 0)
Board(root)
tk.mainloop()
I have code below :
var = DoubleVar()
scale = Scale(root, variable = var, command=self.scalfunc, from_=4, to=40, width=40,tickinterval=0,orient=VERTICAL,length=300,highlightthickness=0, background='#333333', fg='grey', troughcolor='#333333', activebackground='#1065BF')
scale.pack(anchor=CENTER)
scale.place(x=SCwidth/1.2, y=SCheight/15)
and I have button UNDO and anther button REDO
I want when I click in that button I make the Slider Value undo or redo
This code enables the use of Control keys to change the master colors of a tkinter.tk window.
Changes to Scale are stored in list called memory using index int called counter.
Control-z will undo
Control-Z will redo
Control-x will clear the memory
It shouldn't be too difficult to modify it for your needs.
import tkinter as tk
class UndoRedo:
def __init__(self):
self.master = tk.Tk()
self.master.withdraw()
self.master.columnconfigure(0, weight = 1)
self.master.columnconfigure(1, weight = 1)
self.color = 15790320 # #f0f0f0 = SystemButtonFace
self.var = tk.IntVar(self.master, value = self.color)
self.label = tk.Label(self.master, anchor = tk.E)
self.label.grid(row = 0, column = 0, sticky = tk.NSEW)
self.clear() # define memory and counter
self.scroll = tk.Scale(
self.master, orient = "horizontal", resolution = 65793,
label = "Brightness Control", from_ = 0, to = 16777215,
variable = self.var, command = self.control)
self.scroll.grid(row = 1, column = 0, columnspan = 2, sticky = tk.EW)
for k, v in [
( "<Control-z>", self.undo ),
( "<Control-Z>", self.redo ),
( "<Control-x>", self.clear )]:
self.master.bind(k, v)
self.master.geometry("400x86")
self.master.update()
self.master.minsize(329, 86)
self.master.resizable(True, False)
self.master.deiconify()
def display(self):
col = "#" + ("000000" + hex(self.color)[2:])[~5:]
self.var.set(self.color)
self.label["text"] = col
self.master.tk_setPalette(col)
def control(self, n):
self.color = int(n)
self.display()
if self.color not in self.memory:
self.memory.append(self.color)
self.counter = self.counter + 1
def action(self):
self.color = self.memory[self.counter]
self.display()
def undo(self, ev = None):
if self.memory:
self.counter = max(0, self.counter - 1)
self.action()
def redo(self, ev = None):
if self.memory:
self.counter = min(len( self.memory ) - 1, self.counter + 1)
self.action()
def clear(self, ev = None):
self.memory, self.counter = [], 0
self.label["text"] = "cleared"
if __name__ == "__main__":
bright = UndoRedo()
bright.master.mainloop()
If I understand correctly, you could store all positions taken by the slider in a list and use an index pointer to manipulate where it is in the list.
silder_ind = 0
slider_positions = [4] # Or wherever you want to start by default
When the user changes the position of the slider
new_pos = slider.get_current_value() # whatever the appropriate API call is to get the current value
slider_positions.append(new_pos)
slider_ind += 1
When the user hits undo
if (slider_ind - 1) >= 0:
slider_ind -= 1
redo
if (slider_ind + 1) < len(slider_positions):
slider_ind += 1
I have an appliaction which asks the user questions which they should answer.
The application uses pyttsx3 (version 2.9) to generate speech and I would like that while it speaks and only then, a gif animation would play for as long as it speaks.
How can this be accomplished?
For example:
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
And i want the gif animation to start running while runAndWait runs and stop when it stops
Ok I've found another program that works with the GIF images I have.
This program speaks for itself and displays a gif image.
I'm using tkinter Text object for output and a Label to hold the image.
It should allow GIF animes to run but it requires specific information about the GIF.
This runs on windows 10 and pyttsx3 - 2.5
"""
Program outputs text while voice is speaking.
This program works on Python 2.6.14 and Python 3.7.3
"""
import tkinter as tk
from tkinter import filedialog as fido
import random, pyttsx3
class chatter:
terminate = False
def showText( self, m ):
"""talk.showText( m )"""
self.main.insert( "insert", m )
self.master.update( )
self.main.edit_separator( )
def Start( self, name ) ->"":
"""talk.Start( name )"""
self.sentence = name.split( )
def Use( self, name, location, length ) ->"":
"""talk.Use( name, location, length )"""
name = self.sentence.pop( 0 )
self.showText( f"{name} " )
def End( self, name, completed ) ->"":
"""talk.End( name, completed )"""
if len( self.sentence ) > 0:
while len( self.sentence ) > 0:
name = self.sentence.pop( 0 )
self.showText( f"{name}\n" )
else:
self.showText( "\n" )
def Error( self, name, exception ) ->"":
"""talk.Error( name, exception )"""
self.terminate = True
self.engine.stop( )
self.showText( f"\n{name}\n{exception}\n" )
def say( self, m ):
"""talk.say( m )"""
self.engine.say( m, m )
self.engine.runAndWait( )
def intro( self ):
for m in [
"This program works on Python 2.6 and Python 3",
"I am PYTTSX version 2.5" ]:
talk.say( m )
self.master.after( 100, self.imageUpdate, 0 )
def displayInCanvas( self ):
"""talk.displayInCanvas( )"""
self.image = fido.askopenfilename( title = 'Pick Gif' )
w, h = self.image.width() + 14, self.image.height() + 46
self.item = self.canvas.create_image( 2,2, anchor = "nw" )
self.canvas.itemconfig( self.item, image = self.image )
self.master.geometry( f"{w}x{h}" )
self.labelframe[ "text" ] = self.image
def getImage( self ):
"""talk.getImage( )"""
self.item = tk.Label( anchor = "nw" )
self.item.grid( row=0, column=1, sticky="nsew" )
self.image = fido.askopenfilename( title = 'Pick Gif' )
# This requires specific knowledge about the GIF image
# n = number of animation frames
# self.frame = [ tk.PhotoImage( master = self.master, file=self.image, format = 'gif -index %i' %( i ) ) for i in range( n ) ]
self.frame = [ tk.PhotoImage(
master = self.master, file = self.image, format = "gif -index 0" ) ]
self.item.configure( image = self.frame[ 0 ] )
def imageUpdate( self, ind ):
"""imageUpdate( ind )"""
frame = self.frame[ ind ]
ind += 1
print( ind )
# Will play gif infinitely
if ind > 0:
ind = 0
self.item.configure( image = frame )
self.master.after( 100, self.imageUpdate, ind )
def closer( self, ev = None ):
self.master.destroy( )
def __init__( self ):
"""talk.init"""
self.engine = pyttsx3.init( )
self.startUtter = self.engine.connect(
"started-utterance", self.Start )
self.wordsUtter = self.engine.connect(
"started-word", self.Use )
self.endsUtter = self.engine.connect(
"finished-utterance", self.End )
self.erraUtter = self.engine.connect(
"error", self.Error )
self.persona = self.engine.getProperty( "voices" )[~0].id
self.engine.setProperty( "voice", self.persona )
for a,b in [ ("rate", 150 ), ( "volume", 0.25 ) ]:
self.engine.setProperty( a,b )
self.engine.runAndWait( )
self.master = tk.Tk()
self.main = tk.Text(
self.master, undo =1, wrap = "word",
block = 1, width = 80, height = 25 )
self.main.grid( row = 0, column = 0, sticky = "nsew" )
self.master.bind( "<Escape>", self.closer )
self.showText( __doc__ + "\n" )
self.main.update_idletasks( )
self.getImage( ) # load and display gif
self.main.focus_set()
self.master.after( 100, self.intro )
if __name__ == "__main__":
talk = chatter( )
tk.mainloop()
I have a problem, I was working on a code with python 3. the code is about getting news of a website onto my canvas. however I keep getting this error which says:
AttributeError: 'NewsFeed' object has no attribute 'canvas'.
this is my code:
from tkinter import *
import feedparser
root=Tk()
class Achtergrond() :
m_Width = 0
m_Height = 0
m_BgColor = 0
def CreateCanvas(self, master, width, height) :
m_Width = width
m_Height = height
m_BgColor='#14B4E1'
self.canvas = Canvas(master, width=m_Width, height=m_Height)
self.canvas.configure(bg=m_BgColor)
self.canvas.pack()
return(self.canvas)
def create_rectangle(x0, y0 ,x1,y1, color) :
self.canvas.create_rectangle(x0, y0, x1, y1, fill=color)
return
def create_title (self, x, y, title, opmaak):
self.canvas.create_text(x,y,text=title, font= opmaak)
return
def create_newsbox(master,x0,y0,x1,y1,color):
canvas.create_rectangle(x0,y0,x1,y1, fill=color)
return
def SetBackgroundColor(self, kleurcode) :
m_BgColor = kleurcode
self.canvas.configure(bg=m_BgCode)
self.canvas.pack()
return
class NewsFeed ():
Hitem = 0
Nitem = 0
feed = 0
th = 0
rssURL = ""
def UpdateNews(self,path):
self.rssURL = path
self.feed = feedparser.parse(self.rssURL)
self.Nitem = len(self.feed["items"])
return
def ToonEerste(self):
str=""
self.Hitem = 0
for i in range(self.Hitem,self.Hitem+2,1):
if i < self.Nitem:
entry = self.feed["entries"][i]
str += entry.title + "\n\n" + entry.summary + "\n__________________________________________________\n\n"
self.canvas.delete(th)
th = self.canvas.create_text(200,300, width=300, text = str)
return
def ToonVolgende(self):
str=""
self.Hitem += 3
if self.Hitem >= self.Nitem:
Hitem = 0
for i in range(self.Hitem,self.Hitem+2,1):
if i < self.Nitem:
entry = feed["entries"][i]
str += entry.title + "\n\n" + entry.summary + "\n__________________________________________________\n\n"
self.canvas.delete(th)
th = self.canvas.create_text(200,300, width=300, text = str)
return
hoofdscherm = Achtergrond()
a = hoofdscherm.CreateCanvas(root, 1024,600)
b = hoofdscherm.canvas.create_rectangle(30, 120, 360, 500, fill= '#ffffff')
a.create_rectangle(10,10, 1014,80, fill='#ffffff')
a.create_rectangle(30, 120, 360, 500, fill= '#ffffff')
a.create_text(250, 50, text="Harens Lyceum" , font=('Calibri' , 40))
a.configure(bg='#14B4E1')
a.pack()
n = NewsFeed()
n.UpdateNews('http://www.nu.nl/rss/Algemeen')
n.ToonEerste(root)
n.ToonVolgende(root)
root.mainloop()
We would like to have some help with our problem, we don't have much experience. We need to make a screen with raspberry which displays news etc. for school. If you know how we can fix our code we would very much appreciate your guys' help.
Your NewsFeed class instance n doesn't have a Canvas attribute. If you want to pass the Canvas defined in your Achtergrond class instance hoofdscherm to n, you can define it under the class definition for NewsFeed using __init__():
class NewsFeed ():
def __init__(self, canvas):
self.canvas = canvas
...
Then when you initialize your NewsFeed object as n, you can pass the Canvas instance from your Achtergrond class instance hoofdscherm:
n = NewsFeed(hoofdscherm.canvas)
This is a solution to your current issue, but there are other errors in your code that you can see once you modify it.