Getting Input From a Tkinter Class by Another Class - python

I am trying to connect my tkinter code with another program. That is, I am trying to call the GUI file from the the other program and receive input from the GUI program, but I am having issues.
Here is the GUI code called BayeGUI
from tkinter import *
import tkinter.simpledialog
class BayeGUI:
def __init__(self):
window = Tk()
window.title('Graphical User Interface Designed by Gideon')
self.input = 'I am fine Thank you'
frame1 = Frame(window)
frame1.pack()
self.v1 = StringVar()
scrollbar = Scrollbar(frame1)
scrollbar.pack(side = RIGHT, fill = Y)
self.text = Text(frame1, width = 100, height = 30,wrap = WORD, yscrollcommand = scrollbar.set)
scrollbar.config(command = self.text.yview)
self.text.pack()
frame2 = Frame(window)
frame2.pack()
testbtn = Button(frame2,text = 'Test Algorithm',command = self.testAlgorithm)
testbtn.grid(row = 1, column = 1)
return self.input
window.mainloop()
def testAlgorithm(self):
isYes = tkinter.messagebox.askyesno('askyesno', 'Do you want to Test the Algorithm?')
if isYes == True:
self.input = self.text.get("1.0",'end-1c') #This is the input I need
BayeGUI()
This is the main code where I am trying to get value fron Baye GUI.
from BayeGUI import BayeGUI
emails = BayeGUI()
print(emails)

Related

is there a way to grid an extra button while running your program in tkinter correctly?

I'm making an mp3 player app and I want the user to be able to add playlists (which will be buttons in a grid system.
Like so.
However in this state when I'm trying to add a playlist button this happens:
The top buttons and the button i just added get squeezed off and the scrollbar is stuck (I can't use it)
I've tried refreshing by self.playlist_frame.update_idletasks() after running create_playlists() but it doesn't seem to change anything
this is my code so you can test it:
import os
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class MyApp:
def __init__(self):
self.root = tk.Tk()
self.width = self.root.winfo_screenwidth()
self.height = self.root.winfo_screenheight()
self.height = self.root.winfo_screenheight() - int(self.height / 13)
self.root.geometry(f'{self.width}x{self.height}')
self.root.title("Mp3")
self.c = '#14141D'
self.playlists_buttons_list = []
self.playlists = {}
self.helping_d = {}
self.main = ttk.Notebook(self.root)
self.playlists_tab = tk.Frame(self.main)
self.playlist_menu_frame = tk.Frame(self.playlists_tab, bg=self.c)
self.playlists_canvas = tk.Canvas(self.playlists_tab, bg=self.c)
self.playlist_frame = tk.Frame(self.playlists_canvas, bg=self.c)
self.playlists_scrollbar = ttk.Scrollbar(self.playlists_tab, orient='vertical',
command=self.playlists_canvas.yview)
self.add_playlist_win = tk.Toplevel(self.root)
self.add_playlists_button = tk.Button(self.playlist_frame)
self.default_img = Image.open('images/default.png').resize((75, 72))
self.default_img = ImageTk.PhotoImage(self.default_img)
self.add_img = Image.open('images/add.png').resize((50, 50))
self.add_img = ImageTk.PhotoImage(self.add_img)
self.widgets()
self.root.mainloop()
def widgets(self):
self.playlists_tab.place(height=self.height, width=self.width, x=0, y=0)
self.main.add(self.playlists_tab, text="Playlists")
self.main.pack(expand=1, fill="both")
self.playlist_frame = tk.Frame(self.playlists_canvas, bg=self.c)
self.playlists_canvas.create_window((0, 0), window=self.playlist_frame, anchor='center')
self.playlists_canvas.config(bg=self.c)
self.playlists_canvas.place(height=int(self.height / 1.428), width=self.width, x=0, y=int(self.height / 9))
self.add_playlists_button = tk.Button(self.playlists_canvas, image=self.add_img, bg=self.c, bd=0,
command=self.add_playlists)
self.add_playlists_button.place(x=1284, y=75)
self.playlists_scrollbar.pack(side='right', fill='y')
self.playlists_canvas.config(yscrollcommand=self.playlists_scrollbar.set)
self.playlists_canvas.bind('<Configure>', lambda e: self.playlists_canvas.configure(
scrollregion=self.playlists_canvas.bbox('all')))
if os.path.getsize('playlistsnames.txt') != 0:
lines = open('playlistsnames.txt', 'r', encoding='utf-8').read().splitlines()
for i in lines:
self.playlists[i] = []
self.create_playlists()
def create_playlists(self):
self.playlists_buttons_list = []
for i in range(len(self.playlists.keys())):
self.playlists_buttons_list.append(tk.Button(self.playlist_frame, bg=self.c,
text=' ' + list(self.playlists.keys())[i].split('!')[0],
fg='white', image=self.default_img, height=280, width=300))
row = 0
column = 0
for i in self.playlists_buttons_list:
if column > 3:
row += 1
column = 0
if column > 7:
row += 1
column = 0
i.grid(row=row, column=column)
column += 1
def get_name(self):
self.name_of_plst = self.plst_entry.get()
self.playlists[self.name_of_plst] = []
self.create_playlists()
with open('playlistsnames.txt', 'a', encoding='utf-8') as names_file:
names_file.write(self.name_of_plst + '!\n')
def add_playlists(self):
self.add_playlist_win = tk.Toplevel(self.root)
self.name_label = tk.Label(self.add_playlist_win, text='Name:', bg=self.c, fg='pink').pack()
self.plst_entry = tk.Entry(self.add_playlist_win)
self.plst_entry.pack()
self.confirm_btn = tk.Button(self.add_playlist_win, text='Confirm', bg=self.c, fg='pink',
command=self.get_name).pack()
self.add_playlist_win.mainloop()
MyApp()
I should also mention that because I store the playlist names in a file called playlistnames.txt when I rerun the program I can see all the playlist buttons plus the one I created before and things work just fine.
So what I want is making the grid update and work while running the app without having to rerun the app of course
My playlistsnames.txt file has this format:
rock!
metal!
chill!
rap!
jazz!
blues!
hard rock!
trap!
Any suggestions would be helpful!
Thanks in advance!

got Exception in Tkinter callback when do getter setter

so, I want to pass a value between two classes with sparated file by creating a new class as connector between them (getter and setter)
so, there're all of my code:
UIinput.py
from tkinter import *
from getset import getset
from restRFID import restRFID
class UIinput:
varInput = ""
varIN = ""
sset = getset()
def inputDat():
global varIN
ui = Tk()
ui.geometry("300x300")
ui.title("Input Data")
frame1 = Frame(ui)
frame1.pack()
frame2 = Frame(ui)
frame2.pack()
label1 = Label(frame1, text = "Masukkan nama: ")
label1.pack(side = LEFT)
textbox1 = Entry(frame1, bd = 5, width = 20)
textbox1.pack(side = LEFT)
varIN = textbox1.get()
Button1 = Button(ui, text = "Input", command = lambda: UIinput.process(textbox1.get()))
Button1.place(x = 150,y = 50)
ui.mainloop()
def process(dat):
UIinput.sset.set(str(dat))
restRFID.getDat()
UIinput.inputDat()
restRFID.py
from tkinter import *
from getset import getset
class restRFID:
getdat = getset()
def getDat():
ui = Tk()
ui.geometry("300x300")
frame1 = Frame(ui)
ui.title("Get Data")
frame1.pack()
frame2 = Frame(ui)
frame2.pack()
dat = StringVar()
dat.set(str(restRFID.getdat.get()))
label1 = Label(frame1, textvariable = dat)
label1.pack(side = LEFT)
ui.mainloop()
and the last is my code that I use as a setter getter for all the code above this code
getset.py
class getset(object):
def set(self, x):
self.inputdata = x
def get(self):
return self.inputdata
but when I try to compile it I got an error exception:
AttributeError: 'getset' object has no attribute 'inputdata'
but if try implemnt the getter and setter method in getset.py class, it's run succesfully without any errors.

How to write commands to terminal using tkinter?

I wanted to do something like , if i type something in textbox that command would get executed completely
like this
ie the ~Desktop should be displayed to write next command.
but with my code im getting this also there is an error
as you can see ls command gets executed half in second case
my code is
#!/usr/bin/python
import Tkinter
import subprocess
import tkMessageBox
from Tkinter import *
root = Tk()
class HackBar:
def __init__(self,master):
frame=Frame(master,width = 600,height = 250)
#frame.pack()
def printconsole(event):
print("hello dere ")
def retrieve_input(event):
input = self.Text.get("1.0",'end-1c')
#print(input)
#subprocess.call(input,shell=TRUE)
subprocess.Popen(input)
root.quit()
#root = Tk()
#print p.communicate()
self.button1 = Button(root,text = "Execute")
self.button1.bind("<Button-1>",retrieve_input);
self.button1.grid(row = 0,sticky = E)
self.button2 = Button(root,text = " Quit ")
self.button2.bind("<Button-1>",printconsole);
self.button2.grid(row = 1,sticky = E)
self.Text = Text(root,height =4)
self.Text.grid(row = 0,column = 1,rowspan=2)
menu = Menu(root)
def AboutDialog():
tkMessageBox.showinfo('About','For any issues or suggestion contact rushic24#gmail.com ')
root.config(menu = menu)
submenu1 = Menu(menu)
menu.add_cascade(label="Help",menu=submenu1)
submenu1.add_command(label = "About",command = AboutDialog)
b = HackBar(root)
root.mainloop()
i think i need to use the root.quit() and would again need to start root ,
but it is giving the above error.
Any alternate method would also work.

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

Python: Focus on ttk.Notebook tabs

I haven't figured out how to set the focus on a specific tab of a ttk.Notebook. focus_set does not work. Is there any possibility?
Thanks in advance
I was having the same problem. What I found is the 'select' method for notebooks (ttk.Notebook.select(someTabFrame)) solves this problem:
import ttk, Tkinter
mainWindow = Tkinter.Tk()
mainFrame = Tkinter.Frame(mainWindow, name = 'main-frame')
mainFrame.pack(fill = Tkinter.BOTH) # fill both sides of the parent
nb = ttk.Notebook(mainFrame, name = 'nb')
nb.pack(fill = Tkinter.BOTH, padx=2, pady=3) # fill "master" but pad sides
tab1Frame = Tkinter.Frame(nb, name = 'tab1')
Tkinter.Label(tab1Frame, text = 'this is tab 1').pack(side = Tkinter.LEFT)
nb.add(tab1Frame, text = 'tab 1')
tab2Frame = Tkinter.Frame(nb, name = 'tab2')
Tkinter.Label(tab2Frame, text = 'this is tab 2').pack(side = Tkinter.LEFT)
nb.add(tab2Frame, text = 'tab 2')
nb.select(tab2Frame) # <-- here's what you're looking for
mainWindow.mainloop()
python docs for ttk.Notebook:
https://docs.python.org/2/library/ttk.html#ttk.Notebook
I also used this blog post as a model for my code:
http://poquitopicante.blogspot.com/2013/06/blog-post.html
This code based on wordsforthewise's answer to this question. Here you can find example of using select as get and set function, it shown by button that switch between 2 tabs.
small improvement:
import ttk, Tkinter
from pango import Weight
from Tkinter import Button
tab2Frame = None
tab1Frame = None
def switchTab():
if nb.select()[-1] == "1":
nb.select(tab2Frame)
elif nb.select()[-1] == "2":
nb.select(tab1Frame)
mainWindow = Tkinter.Tk()
mainWindow.geometry("%dx%d+0+0" % (200, 200))
mainFrame = Tkinter.Frame(mainWindow, name = 'main-frame')
mainFrame.pack(fill = Tkinter.BOTH) # fill both sides of the parent
button = Button(mainWindow, text = "Switch", command = switchTab)
button.configure(width = 15, activebackground = "#6f6Fff")
button.pack()
nb = ttk.Notebook(mainFrame, name = 'nb')
nb.pack(fill = Tkinter.BOTH, padx=2, pady=3) # fill "master" but pad sides
tab1Frame = Tkinter.Frame(nb, name = 'tab1')
Tkinter.Label(tab1Frame, text = 'this is tab 1').pack(side = Tkinter.LEFT)
nb.add(tab1Frame, text = 'tab 1')
tab2Frame = Tkinter.Frame(nb, name = 'tab2')
Tkinter.Label(tab2Frame, text = 'this is tab 2').pack(side = Tkinter.LEFT)
nb.add(tab2Frame, text = 'tab 2')
mainWindow.mainloop()

Categories