Python and GeoTiff images, scrolling problem - python

I have a problem, this is the code that opens the GeoTiff mini photo gallery window but the scrolling does not work for me. What is wrong in the code? I have the impression that the rewind and the photos are two separate things, I don't know how to "glue" them together. Thank you very much for your help.
import tkinter as tk
import glob
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import rasterio as rio
from rasterio.plot import show
SIZE_X = 100
SIZE_Y = 100
class Icon:
def __init__(self, root):
self.root = root
self.ybar = tk.Scrollbar(self.root)
self.item_canvas = tk.Canvas(self.root, width=354, height=401,
yscrollcommand=self.ybar.set)
self.ybar.configure(command=self.item_canvas.yview)
self.item_canvas.configure(scrollregion=(0, 0, 1000, 1000))
self.item_canvas.configure(background='#d8d8d9')
self.ybar.pack(side=tk.RIGHT, fill=tk.Y)
self.item_canvas.pack(side=tk.LEFT, expand=tk.TRUE, fill=tk.BOTH)
self.get_icons()
def get_dir(self):
link = r'work_dir/*.txt'
with open(link) as f:
self.file_photo = f.read()
self.link_to_dir = glob.glob(self.file_photo.rsplit('/', 1)[0] + '/*.tif')
self.number = len(self.link_to_dir)
def get_icons(self):
'''Method to add a mini gallery'''
self.get_dir()
FIGSIZE = 2.5
self.counter = -1
if self.number <= 2:
for i in range(0, self.number):
self.fig = Figure(figsize=(FIGSIZE, FIGSIZE), dpi=60)
self.canvasGeo = FigureCanvasTkAgg(self.fig, self.root)
self.canvasGeo.get_tk_widget().place(x=i * 220, y=10)
with rio.open(self.link_to_dir[i]) as src_plot:
show(src_plot, ax=self.fig.add_subplot())
self.canvasGeo.draw()
elif self.number > 2:
k = int()
y = []
for i in range(0, self.number):
if i % 2 == 0:
k = i
y.append(k)
for j in range(0, self.number):
self.counter += 1
if (j * 220) <= 220:
self.fig = Figure(figsize=(FIGSIZE, FIGSIZE), dpi=60)
self.canvasGeo = FigureCanvasTkAgg(self.fig, self.root)
self.canvasGeo.get_tk_widget().place(x=10 + j * 190, y=10)
with rio.open(self.link_to_dir[y[j]]) as src_plot:
show(src_plot, ax=self.fig.add_subplot())
self.canvasGeo.draw()
else:
self.fig = Figure(figsize=(FIGSIZE, FIGSIZE), dpi=60)
self.canvasGeo = FigureCanvasTkAgg(self.fig, self.root)
self.canvasGeo.get_tk_widget().place(x=(-175 * y[j]) + j * 180, y=85*y[j])
with rio.open(self.link_to_dir[y[j]]) as src_plot:
show(src_plot, ax=self.fig.add_subplot())
self.canvasGeo.draw()
else:
tk.Label(self.root, text='Wrong Value').place(x=220, y=10)
if __name__ == '__main__':
root = tk.Tk()
Icon(root)
root.mainloop()

New code:
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
class Icon(Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_images_button = Button(self)
self.select_images_button["text"] = "Select Images"
self.select_images_button["command"] = self.select_images
self.select_images_button.pack()
self.quit = Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack()
self.images_label = Label(self)
self.images_label.pack()
self.scale = Scale(self, from_=0, to=100, orient=HORIZONTAL,
command=self.resize_image)
self.scale.set(100)
self.scale.pack()
def select_images(self):
self.files = filedialog.askopenfilenames(initialdir = "/", title = "Select file",
filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
self.load_image()
def load_image(self):
self.image = Image.open(self.files[0])
self.resized_image = self.image.resize((100, 100), Image.ANTIALIAS)
self.photo = ImageTk.PhotoImage(self.resized_image)
self.images_label.configure(image=self.photo)
self.images_label.image = self.photo
def resize_image(self, value):
size = int(value)
self.resized_image = self.image.resize((size, size), Image.ANTIALIAS)
self.photo = ImageTk.PhotoImage(self.resized_image)
self.images_label.configure(image=self.photo)
self.images_label.image = self.photo
root = Tk()
app = Icon(master=root)
app.mainloop()

Related

Image disappear when I draw a canvas on the same root. Tkinter, Python

I am trying to create a gui. But I stack in here, because whenever I clicked to button2 canvas show up but first image disappear. I want to see both of them, one of them on the right and the other one on the left. I tried to resize but it doesn't effect anything. For explanation, I upload .txt file and and transform it to image. Then I plot it in frame left and then plot first column of the array in the left frame.
class GUI(Frame):
def __init__(self):
self.array = None
Frame.__init__(self)
self.frame_left = tk.Frame(root, width=540, height=640, bd="2")
self.frame_left.grid(row=0, column=0)
self.frame_right = tk.Frame(root, width=540, height=640, bd="2")
self.frame_right.grid(row=0, column=1)
self.button = tk.Button(self.frame_left, text="Resim SeƧ", command=self.open_image)
self.button.pack(side='top')
# def imgResize(img): ### burasi image resize
# basewidth = 500
# wpercent = (basewidth / float(img.size[0]))
# hsize = int((float(img.size[1]) * float(wpercent)))
# img = img.resize((basewidth, hsize), Image.ANTIALIAS)
# return img
def a_scan(self):
if hasattr(self, 'canvas'):
self.canvas.get_tk_widget().destroy()
self.image = Image.open("output.png")
self.im_np = np.array(self.image)
self.img = np.array(self.im_np)
self.imga = (self.img - np.min(self.img)) / (np.ptp(self.img).astype(int))
self.a = self.imga[:, 0] ##ilk sutundaki degerler'''
self.b=self.a.shape[0] ##ilk sutunda kac tane deger oldugu'''
self.b=np.arange(0,self.b)
self.a=np.array(self.a)
self.array = np.stack((self.a, self.b), axis=-1)
fig, ax = plt.subplots()
ax.plot(self.b, self.a)
ax.set(xlabel='Index', ylabel='Intensity', title='A-Scan')
ax.grid()
self.canvas = FigureCanvasTkAgg(fig, self.frame_right)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=RIGHT, fill=Y)
def open_image(self):
filepath = filedialog.askopenfilename()
if hasattr(self, 'canvas'):
self.canvas.get_tk_widget().destroy()
if hasattr(self, 'label'):
self.label.destroy()
self.button2.destroy()
if filepath.endswith(".txt"):
self.data = np.loadtxt(filepath)
self.data = np.array(self.data)
self.data = (255 * (self.data - np.min(self.data))) / (np.ptp(self.data).astype(int))
self.data = np.transpose(self.data, axes=None)
self.image = Image.fromarray(np.uint8(self.data))
self.image.save("output.png")
self.image = ImageTk.PhotoImage(self.image)
self.label = Label(self.frame_left, image=self.image)
self.label.pack(side=LEFT)
self.button2 = tk.Button(self.frame_left, text="A scan goster", command=self.a_scan)
self.button2.pack(side=RIGHT)
else:
image = Label(root, image=filepath)
image.pack()
root = tk.Tk()
root.title('YNR')
root.geometry('1080x640')
app = GUI()
app.mainloop()
here is my code. Thanks.

How can I print all the classification results to the Text widget on my GUI?

I have a GUI that classifies images as right or wrong. How can I print all the results in the text widget such that all of them will be printed out after clicking the user control button? When I click that button, I expect to have all the answers being printed in the widget. However, it prints the last result only
here are my codes
from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog
from PIL import Image, ImageTk
import os
import cv2
import numpy as np
import time
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
#self.button1 = Button(self,text='Image Selector',bg= 'blue',width=15,height=2,command=self.browseFiles)
#self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button2 = Button(self,text='User control',bg= 'blue',width=15,height=2,command=self.Image_Classification)
self.button2.grid(column=0,row=1,sticky='W',pady=5,padx=150)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#self.button4 = Button(self,text='Method 2',width=10,height=2)
#self.button4.grid(column=0,row=2,sticky='W',pady=5)
#Text widget for inserting result
############################################################################################
self.text1 = Text(self,height=2,width=20,state=NORMAL)
self.text1.grid(column=2,row=1,sticky='E',padx=5)
#self.text1.configure(bg='cyan')
#self.canvas2 = Canvas(self,height=10,width=20,state=NORMAL)
#self.canvas2.grid(column=2,row=2,sticky='E',padx=5)
self.text3 = Text(self,height=2,width=20,state=NORMAL)
self.text3.grid(column=2,row=3,sticky='E',padx=5)
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
#Label widget
############################################################################################
self.label1 = Label(self,text="Mode", bg = 'red', width=10,height=2,anchor="center")
self.label1.grid(column=0,row=0,sticky='W',padx=120)
self.label2 = Label(self,text="Inspection",bg = 'red',width=20,height=2,anchor="center")
self.label2.grid(column=2,row=0,sticky='E',padx=50)
self.label3 = Label(self,text="Image",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
self.label4 = Label(self,text="Classification",bg = 'red',width=10,height=2,anchor="center")
self.label4.grid(column=1,row=1,sticky='E',pady=10)
#self.label5 = Label(self,text="Result 2(Black Spot)",width=30,height=2,anchor="e")
#self.label5.grid(column=1,row=2,sticky='E',pady=10)
self.label6 = Label(self,text="Time",bg = 'red',width=10,height=2,anchor="center")
self.label6.grid(column=1,row=3,sticky='E',pady=10)
'''def browseFiles(self):
self.filename = filedialog.askopenfilename(initialdir = '/',title = "Select a File",
filetypes = [("image",".jpeg"),("image",".png"),("image",".jpg")])
start=time.time()
self.imageFile = ImageTk.PhotoImage(file=self.filename)
self.canvas.create_image(50,10,image=self.imageFile,anchor=NW)
self.img = cv2.imread(self.filename)
self.hist = cv2.calcHist([self.img], [0], None, [256], [0,256])
self.mean_px = cv2.mean(self.img)
self.max_nums = max(self.hist); self.max_num = str(self.max_nums)
self.max_num_px= np.where(self.hist==self.max_nums)[0]+1; self.max_num_px = str(self.max_num_px)
self.min_nums = min(self.hist); self.min_num = str(self.min_nums)
self.min_num_px= np.where(self.hist==self.min_nums)[0]+1; self.min_num_px = str(self.min_num_px)
self.hist_2_num = round((self.max_nums*(2/5))[0])
self.hist_2_min_num = self.hist[self.hist>=self.hist_2_num][0]
self.hist_2_max_num = self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1]
self.hist_2_min_val = np.where(self.hist==self.hist_2_min_num)[0][0]+1
self.hist_2_max_val = max(np.where(self.hist==self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1])[0])
self.hist_2_diff = self.hist_2_max_val - self.hist_2_min_val
self.results = []
if self.hist_2_diff>50:
self.results.append('good')
else:
self.results.append('bad')
for choices in self.results:
self.text1 = Text(self,height=2,width=20,state=NORMAL)
self.text1.insert(END,str(choices))
self.text1.grid(column=2,row=1,sticky='E',padx=5)
end=time.time()
Time_elapsed='{:.3f}s'.format(end-start)
text3 = Text(self,height=2,width=20,state=NORMAL)
text3.insert(END,str(Time_elapsed))
text3.grid(column=2,row=3,sticky='E',padx=5)'''
def Image_Classification(self):
start=time.time()
for self.i in range(1,31):
for self.j in range(1,11):
self.filename = 'Path/Folder_'+str(self.i)+'/'+str(self.j)+'.jpg'
self.img = cv2.imread(self.filename)
self.hist = cv2.calcHist([self.img], [0], None, [256], [0,256])
self.mean_px = cv2.mean(self.img)
self.max_nums = max(self.hist); self.max_num = str(self.max_nums)
self.max_num_px= np.where(self.hist==self.max_nums)[0]+1; self.max_num_px = str(self.max_num_px)
self.min_nums = min(self.hist); self.min_num = str(self.min_nums)
self.min_num_px= np.where(self.hist==self.min_nums)[0]+1; self.min_num_px = str(self.min_num_px)
self.hist_2_num = round((self.max_nums*(2/5))[0])
self.hist_2_min_num = self.hist[self.hist>=self.hist_2_num][0]
self.hist_2_max_num = self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1]
self.hist_2_min_val = np.where(self.hist==self.hist_2_min_num)[0][0]+1
self.hist_2_max_val = max(np.where(self.hist==self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1])[0])
self.hist_2_diff = self.hist_2_max_val - self.hist_2_min_val
self.results = []
if self.hist_2_diff>50:
self.results.append('{}: good'.format(self.j))
print('{}: good'.format(self.j))
else:
self.results.append('{}: bad'.format(self.j))
print('{}: bad'.format(self.j))
for choices in self.results:
self.text1 = Text(self,height=2,width=20,state=NORMAL)
self.text1.insert(END,str(choices))
self.text1.grid(column=2,row=1,sticky='E',padx=5)
#self.text1.tag_config(background='blue')
self.j+=1
end=time.time()
Time_elapsed='{:.3f}s'.format(end-start)
text3 = Text(self,height=2,width=20,state=NORMAL)
text3.insert(END,str(Time_elapsed))
text3.grid(column=2,row=3,sticky='E',padx=5)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='Cyan'
app.title("Trial")
app.mainloop()
My results
The expected results
Test images
You should not create new Text widgets to store the result in each iteration. As you have already created those Text widgets for showing results and time elapsed inside initialize(), you can just insert the results into those widgets after the for loop:
def Image_Classification(self):
self.results = []
start = time.time()
for self.i in range(1, 31):
for self.j in range(1, 11):
self.filename = 'Path/Folder_'+str(self.i)+'/'+str(self.j)+'.jpg'
self.img = cv2.imread(self.filename)
self.hist = cv2.calcHist([self.img], [0], None, [256], [0,256])
self.mean_px = cv2.mean(self.img)
self.max_nums = max(self.hist); self.max_num = str(self.max_nums)
self.max_num_px = np.where(self.hist==self.max_nums)[0]+1; self.max_num_px = str(self.max_num_px)
self.min_nums = min(self.hist); self.min_num = str(self.min_nums)
self.min_num_px = np.where(self.hist==self.min_nums)[0]+1; self.min_num_px = str(self.min_num_px)
self.hist_2_num = round((self.max_nums*(2/5))[0])
self.hist_2_min_num = self.hist[self.hist>=self.hist_2_num][0]
self.hist_2_max_num = self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1]
self.hist_2_min_val = np.where(self.hist==self.hist_2_min_num)[0][0]+1
self.hist_2_max_val = max(np.where(self.hist==self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1])[0])
self.hist_2_diff = self.hist_2_max_val - self.hist_2_min_val
result = 'good' if self.hist_2_diff > 50 else 'bad'
self.results.append(f'{self.i}.{self.j}: {result}')
end = time.time()
time_elapsed = f'{end-start:.3f}s'
self.text3.delete('1.0', END)
self.text3.insert(END, time_elapsed)
self.text1.delete('1.0', END)
for result in self.results:
self.text1.insert(END, f'{result}\n')
Update: added scrollbar for self.text1:
def initialize(self):
...
self.text1 = Text(self, height=2, width=20, state=NORMAL)
self.text1.grid(column=2, row=1, sticky='nse', padx=5)
self.scrollbar1 = Scrollbar(self, orient=VERTICAL, command=self.text1.yview)
self.scrollbar1.grid(column=3, row=1, sticky='ns')
self.text1.config(yscrollcommand=self.scrollbar1.set)
...

Showing matplotlib plots from function in tkinter

I have a problem regarding showing pyplots in tkinkter. I have a function plot_function that returns 4 matplotlib.pyplot-plots. I want to be able to show these plots in a tkinter GUI, and show one plot in the beginning and display the other three with two "next" and "previous" buttons. The plot_funtion is only run once.
At the moment I'm trying to do the following (simplified):
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class GUI:
def plot_function(self):
...
# Generating plots #
...
self.plots = [plt1, plt2, plt3, plt4]
self.init_plots()
def init_plots(self): # Showing the inital plot, plt1
self.plot_ctr = 0
fig = plt.Figure(figsize=(5,4), dpi = 80)
plot1 = fig.add_subplot(111)
plot1.show(self.plots[0])
first_fig = FigureCanvasTkAgg(fig,self.frame1)
first_fig.draw()
first_fig.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
self.master.update_idletasks()
def next_plot(self):
if self.plot_ctr < 3:
self.plot_ctr += 1
else:
self.plot_ctr = 0
self.first_fig.config(image = self.plots[self.plots_ctr])
self.master.update_idletasks()
def prev_plot(self):
if self.plot_ctr > 0:
self.plot_ctr -= 1
else:
self.plot_ctr = 3
self.first_fig.config(image = self.plots[self.plots_ctr])
self.master.update_idletasks()
def __init__(self, master):
self.master = master
self.frame1 = tk.Frame(self.master, relief = tk.RAISED, highlightbackground = "black", highlightthickness = 1)
self.frame1.pack(side = tk.TOP, fill=tk.BOTH, expand=True)
self.next_btn = tk.Button(self.frame1, text = "Next plot", width = 10, command = self.next_plot)
self.prev_btn = tk.Button(self.frame1, text = "Previous plot", width = 10, command = self.prev_plot)
self.prev_btn.pack(side = tk.LEFT, padx = 10, pady = 10)
self.next_btn.pack(side = tk.LEFT, padx = 10, pady = 10)
root = tk.Tk()
my_gui = GUI(root)
root.mainloop()
I feel very unsure on how to properly use TkAgg and would be very grateful on any tips on how I would get this to work.
Here is an example showing how you could organize your code to rotate a sequence of matplotlib figures embedded in a tkinter window
import matplotlib
import tkinter as tk
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class Data:
def __init__(self):
self.x = list(range(10))
self.y0 = self.x[:]
self.y1 = [5 for _ in range(10)]
self.y2 = [-y for y in self.y0]
self.d = [self.y0, self.y1, self.y2]
def get_next_dataset(self):
y = self.d.pop(0)
self.d.append(y)
return self.x, y
class MPLGraph(Figure):
def __init__(self, data):
Figure.__init__(self, figsize=(5, 5), dpi=100)
self.data = data
def obtain_next_figure(self):
self.plot = self.add_subplot(111)
self.plot.plot(*self.data.get_next_dataset())
return self
class GraphPage(tk.Frame):
def __init__(self, parent, graphs):
tk.Frame.__init__(self, parent)
self.title_label = tk.Label(self, text="Graph Page Example")
self.title_label.pack()
self.pack()
self.next_graph_btn = tk.Button(self, text='next graph', command=self.obtain_next_figure)
self.next_graph_btn.pack()
self.graphs = graphs
self.obtain_next_figure()
def obtain_next_figure(self):
try: # protects against AttributeError the first time when self.figure_widget not yet exists yet
self.figure_widget.destroy()
except AttributeError:
pass
self.add_mpl_figure(self.graphs.obtain_next_figure())
def add_mpl_figure(self, fig):
self.mpl_canvas = FigureCanvasTkAgg(fig, self)
self.figure_widget = self.mpl_canvas.get_tk_widget()
self.figure_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
if __name__ == '__main__':
root = tk.Tk()
graph_page = GraphPage(root, MPLGraph(Data()))
root.mainloop()

How to browse an image and display it in Python?

I have this code here:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
class Root(Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Python Tkinter Dialog Widget")
self.minsize(640, 400)
self.labelFrame = ttk.LabelFrame(self, text = "Open File")
self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select A File", filetype =
(("jpeg files","*.jpg"),("all files","*.*")) )
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
root = Root()
root.mainloop()
I am trying to display the image I have chosen in browsing menu.
Currently I have self.label.configure(text = self.filename) to give me return filename, but how can I display the image itself?
Maybe this is what you're looking for:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk
class Root(Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Python Tkinter Dialog Widget")
self.minsize(640, 400)
self.labelFrame = ttk.LabelFrame(self, text = "Open File")
self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select A File", filetype =
(("jpeg files","*.jpg"),("all files","*.*")) )
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
img = Image.open(self.filename)
photo = ImageTk.PhotoImage(img)
self.label2 = Label(image=photo)
self.label2.image = photo
self.label2.grid(column=3, row=4)
root = Root()
root.mainloop()

having trouble in setting up a calendar in tkinter

i have a small ui programm and i need to display a calendar in it or a date picker . (NOTE : userid and password is root")**
i have tried this code :
from Tkinter import *
from PIL import Image, ImageTk
import ttkcalendar
class App():
def __init__(self):
pass
root = Tk()
root.configure(bg='black')
root.attributes('-alpha', 0.0)
def mainWindow(self):
self.root.geometry('{}x{}'.format(600,400))
self.root.attributes('-alpha', 1)
self.root.configure(bg='#404040')
self.ttkcal = ttkcalendar.Calendar(self.root,firstweekday=calendar.SUNDAY)
self.ttkcal.pack()
self.root.wm_title("time sheet management system")
# Create the toolbar as a frame
self.toolbar = Frame(self.root, borderwidth=1, relief='raised')
self.toolbar.configure( bg = '#838383')
# Load all the images first as PNGs and use ImageTk to convert
# them to usable Tkinter images.
self.img1 = Image.open('NewIcon.png')
self.useImg1 = ImageTk.PhotoImage(self.img1)
self.img2 = Image.open('LoadIcon.png')
self.useImg2 = ImageTk.PhotoImage(self.img2)
self.img3 = Image.open('SaveIcon.png')
self.useImg3 = ImageTk.PhotoImage(self.img3)
# Set up all the buttons for use on the toolbars.
newBtn = Button(self.toolbar, image=self.useImg1, command=self.callback)
newBtn.pack(side=LEFT, fill=X)
loadBtn = Button(self.toolbar, image=self.useImg2, command=self.callback)
loadBtn.pack(side=LEFT, fill=X)
saveBtn = Button(self.toolbar, image=self.useImg3, command=self.callback)
saveBtn.pack(side=LEFT, fill=X)
# Add the toolbar
self.toolbar.pack(side=TOP, fill=X)
"""
#create a frame
self.infoArea= Frame(self.root, borderwidth=2,height=40,width=100, relief='raised',bg='red')"""
self.root.mainloop()
"""
# Set up a Text box and scroll bar.
self.scrollbar = Scrollbar(self.root)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.text = Text(self.root)
self.text.pack()
self.text.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.text.yview)"""
def loginClick(self):
self.userid = self.txt1.get()
self.password = self.txt2.get()
print self.userid,self.password
if self.password == 'root' and self.userid == 'root':
self.wi.destroy()
self.mainWindow()
def callback(self):
print "A button was pressed"
def login(self):
self.wi = Toplevel (self.root)
#self.wi.geometry('{}x{}'.format(200,200))
self.wi.configure(bg='#404040')
self.wi.overrideredirect(1)
self.wi.update_idletasks()
self.w = self.wi.winfo_screenwidth()
self.h = self.wi.winfo_screenheight()
self.size = tuple(int(_) for _ in self.wi.geometry().split('+')[0].split('x'))
self.x = self.w/2 - self.size[0]/2
self.y = self.h/2 - self.size[1]/2
self.wi.geometry("%dx%d+%d+%d" % (self.size + (self.x, self.y)))
self.wi.geometry('{}x{}'.format(400,200))
self.frame1 = Frame ( self.wi,bg='#404040' )
self.frame1.pack(side=BOTTOM,fill=X)
self.butt1 = Button(self.frame1,text= "Cancel" , bg = '#838383',fg='white',command = self.wi.destroy)
self.butt1.pack(side=RIGHT,padx=1)
self.butt2 = Button(self.frame1,text= "Login" ,bg = '#838383',fg='white',command = self.loginClick)
self.butt2.pack(side=RIGHT)
"""self.frame2 = Frame ( self.wi,bg='green' )
self.frame2.pack(side=BOTTOM,fill=BOTH)"""
self.lab1 = Label (self.wi,text='UserID',bg='#404040',fg='white')
#self.lab1.pack(side=LEFT,padx=60,pady=20)
self.lab1.place(x=60,y=20)
self.lab2 = Label (self.wi,text='Password',bg='#404040',fg='white')
#self.lab1.pack(side=LEFT,padx=60,pady=20)
self.lab2.place(x=60,y=60)
self.txt1 = Entry( self.wi)
self.txt1.place(x=140,y=20)
self.txt2 = Entry( self.wi,show='*')
self.txt2.place(x=140,y=60)
"""
self.label = Label(self.wi,text="UserID",bg='#838383',fg='white')
self.label.place("""
self.wi.mainloop()
if __name__ == "__main__":
a = App()
#a.root.mainloop()
a.login()
but it is giving error that "name calendar not defined". how can i solve this ?
or is there any other way to implement a calendar or date picker in tkinter.
The code is using calendar module, but it is not importing the module.
self.ttkcal = ttkcalendar.Calendar(self.root, firstweekday=calendar.SUNDAY)
^^^^^^^^^^^^^^^
Simply adding following import statement will solve the problem.
import calendar

Categories