I'm having some trouble with tkinter's create_text. I'm trying to iterate through a list and have create_text output each item in the list one by one. I can't figure this out, as every time I've tried, it does not work the way I want it to. Here's some code that exemplifies the issue:
class GUI(Frame):
def __init__(self, master):
self.test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.c = Canvas(master, width=300, height=300)
self.c.pack()
for items in self.test_list:
items = items
for i in range(0, 300, 100):
for j in range(0, 300, 100):
self.c.create_text(j + 25, i + 20, text=items)
root = Tk()
root.title("Test")
root.geometry("300x300")
GUI(root)
mainloop()
Thank you and I appreciate the help.
Your code had severe indentation problems.
Further, you did not call mainloop on any object.
Then, the position of the objects on the canvas was outside the visible window:
I fixed the code so it runs, and displays something on the canvas; from there, you can modify it to suit your needs.
import tkinter as tk
class GUI(tk.Frame):
def __init__(self, master):
self.test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.c = tk.Canvas(master, width=300, height=300)
self.c.pack()
for idx, elt in enumerate(self.test_list):
row = (idx // 3 + 5) * 20
col = (idx % 3 + 5) * 20
self.c.create_text(row, col, text=elt)
if __name__ == '__main__':
root = tk.Tk()
root.title("Test")
root.geometry("300x300")
GUI(root)
root.mainloop()
This has two outer loops.
# iterates, items == 9 now
for items in self.test_list:
items = items
# uses 9 over and over
for i in range(0, 300, 100):
for j in range(0, 300, 100):
self.c.create_text(j + 25, i + 20, text=items)
Maybe try this instead.
for items in self.test_list:
for i in range(0, 300, 100):
for j in range(0, 300, 100):
self.c.create_text(j + 25, i + 20, text=items)
Related
I would like to utilize a tkinter window with integrated matplotlib graphs that cycle every x seconds. However, this is what I have and I am stuck. Any help would be greatly appreciated. Thank you!
import time
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
root = tk.Tk()
root.geometry('500x500')
x = [1, 2, 3, 4, 5]
y = [[3, 6, 1, 9, 2], [2, 0, 1, 4, 6], [6, 3, 8, 2, 0]]
fig = plt.figure(figsize=(5,5))
i = 0
while i < len(y):
plt.plot(x, y[i])
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
time.sleep(1)
plt.clf()
i += 1
root.mainloop()
What you're looking for is after(). You'll likely have an easier time if you wrap everything up in a simple Root class, so I've done that here.
# imports go here as usual...
class Root(tk.Tk):
def __init__(self):
super().__init__() # init tk.Tk()
self.geometry('500x500')
self.x = [1, 2, 3, 4, 5]
self.y = [[3, 6, 1, 9, 2], [2, 0, 1, 4, 6], [6, 3, 8, 2, 0]]
self.fig = plt.figure(figsize=(5, 5))
# set up the canvas
self.canvas = FigureCanvasTkAgg(fig, master=root)
self.canvas.get_tk_widget().pack()
# begin cycling plots, starting with index 0
self.index = 0
self.cycle_plots(self.index)
def cycle_plots(self, index):
plt.clf # clear plot here
self.index += 1 # go to the next index
if self.index >= len(self.y):
self.index = 0 # wrap around
plt.plot(self.x, self.y[self.index])
self.canvas.draw() # update the canvas
# after 1000mS, call this function again
self.after(1000, lambda i=self.index: self.cycle_plots(i))
if __name__ == '__main__': # run the app!
root = Root()
root.mainloop()
Using a class makes it easier to pass your UI objects - like the Canvas - around between functions (methods). Here, self refers to your Root class, so anything inside it can share variables with self.<varname>, like self.canvas
How to edit this class to obtain n0 in the PPP? I am not obtaining the initial number in the sequence. Thanks
class P():
def __init__(self, n0):
self.n = n0
def __iter__(self):
return self
def __next__(self):
if self.n == 1:
raise StopIteration
self.n = self.n - 1
return self.n
nmax = 10
PP = P(nmax)
PPP = []
for j in PP:
PPP.append(j)
print(PPP)
Current output:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
Desired output:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Store the value before decrementing it
def __next__(self):
if self.n == 1:
raise StopIteration
num = self.n
self.n = self.n - 1
return num
#[10, 9, 8, 7, 6, 5, 4, 3, 2]
import random as rd
def lottery_number():
num = int(number.get())
for i in range(num):
lotto_list = list(range(1,46)) #from 1 to 45
rd.shuffle(lotto_list) #shuffle
lotto_list1 = lotto_list[:6]
lotto_list1.sort() #sorting
answer = '{} Auto'.format(i), lotto_list1
result.config(text=answer)
from tkinter import *
window = Tk()
label = Label(window, text = 'press lottery game number.')
label.pack()
number =Entry(window, width = 30)
number.pack()
btn = Button(window, text = 'Click', fg = 'blue', command = lottery_number)
btn.pack()
result = Label(window, text = 'Result')
result.pack()
window.mainloop()
the result is just one. for example, {1} Auto 3, 5, 9, 30 ,33
I want print multiple results like below
{1} Auto 3, 5, 9, 30 ,33
{2} Auto 4, 6, 9, 23 ,44
{3} Auto 1, 7, 9, 20 ,26
thanks .
Actually, I want print like this below
{A} Auto 3, 5, 9, 30 ,33
{B} Auto 4, 6, 9, 23 ,44
{C} Auto 1, 7, 9, 20 ,26
list_1 is generated each time new
list_2 is unchangeable
In window is printed list_1 in default black colour and i want to make red numbers if they occur in list_2
import tkinter as tk
from tkinter import Label
from random import randint
list_1 = [randint(1, 100) for i in range(12)]
list_2 = [2, 5, 8, 9, 14, 26, 28, 34, 43, 51, 55, 60, 77]
root = tk.Tk()
label = tk.Label(root, text=list_1, padx=15, pady=15)
label.pack()
root.mainloop()
I've tried like this:
if list_2 in list_1:
label.config(fg='red')
or this:
for i in list_2:
for i in list_1:
label.config(fg='red')
But nothing works. Where is mistake?
To check for common hashable items in lists you may want to use sets:
if set(list_2) & set(list_1):
label.config(fg='red')
Or
if any(n in set(list_2) for n in list_1):
label.config(fg='red')
You can also use any and a generator expression:
if any(n in list_2 for n in list_1):
label.config(fg='red')
But its slower and less pythonic.
I have extracted a list from a tree using BFS
solution= [[6], [0, 7], [None, 3, None, 8], [2, 5, None, 9], [1, None, 4, None, None, None], [None, None, None, None]]
How do i print it as a horizontal tree?
I was trying to print it using
def _print_tree(n=0,height,solution):
if n > height:
return
for j in range(len(solution[n])):
if solution[n][j]== None:
print(' ' * (2 ** (height - n + 1) - 1),end='')
else:
print(' ' * (2 ** (height - n + 1) - 1), end='')
print(' ',solution[n][j], end='')
But it gives
I've played around and here is the result
nonechar = 'N'
spacechar = '_'
solution = [[6], [0, 7], [None, 3, None, 8], [2, 5, None, 9], [1, None, 4, None, None, None], [None, None, None, 4],[None, 3]]
for i in range(1, len(solution)):
for j in range(len(solution[i-1])):
if (solution[i-1][j] == None):
solution[i].insert(2*j, None)
solution[i].insert(2*j+1, None)
N = len(solution[-1]) * 2 - 1
offset = (N - 1) / 2
spacing = 0
for i in range(len(solution)):
line = spacechar * int(offset)
for j in range(len(solution[i])):
if (solution[i][j] == None):
line += nonechar
else:
line += str(solution[i][j])
if (j != len(solution[i]) - 1):
line += spacechar * int(spacing)
line += spacechar * int(offset)
print(line)
spacing = offset
offset = (offset - 1) / 2
What I basically did is fill the solution list with the missing data so that each next sub-list has two times more values than the previous one. For each j-th element of the i-th sub-list there are values under [i+1][2*j] and [i+1][2*j+1]. Then I just print out the result using ASCII art, having calculated required offsets and spacing. The limitations here are that you can only use digits 0-9 in order not to screw up my tree. You'll have to figure out the way to solve it on your own :)
Oh, yeah. The output looks like this (feel free to change characters for missing values and spaces):
_______________________________________________________________6_______________________________________________________________
_______________________________0_______________________________________________________________7_______________________________
_______________N_______________________________3_______________________________N_______________________________8_______________
_______N_______________N_______________2_______________5_______________N_______________N_______________N_______________9_______
___N_______N_______N_______N_______1_______N_______4_______N_______N_______N_______N_______N_______N_______N_______N_______N___
_N___N___N___N___N___N___N___N___N___N___N___N___N___4___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N___N_
N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_3_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N_N