Related
Here's the code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import sys
class TwitterBot:
def __init__(self, username, password):
self.username = username
self.password = password
entry_user = tk.Entry(lower_frame, bg="white", fg='black', bd=0)
#entry_user.insert(0, "Username")
#entry_user.bind("<Button-1>", del_value_user)
entry_user.pack(expand = "yes")
entry_pass = tk.Entry(lower_frame, bg="white", fg='black', bd=0)
#entry_pass.insert(0, "Password")
#entry_pass.bind("<Button-1>", del_value_pass)
entry_pass.pack(expand = "yes")
sasha = TwitterBot(entry_user.get(), entry_pass.get())
The entry never send the values I typed in into sasha = TwitterBot(entry, entry2)
Meaning I want that inside tkinter interface, I type in two entries that supposed to be username and password and when I execute the function those values get injected. I think the problem is that self.username and self.password are defined inside of the __init__ and so if those entries stay empty at the launch so i cant get them to inject. cause I can print my entry.get() values. I just cant make them replace the two first parameters of my __init__ function. Does anybody knows how to help?
Try this:
import tkinter as tk
class TwitterBot:
def __init__(self, username, password):
print("Username =", username, " Password =", password)
self.username = username
self.password = password
def create_bot(event=None):
sasha = TwitterBot(entry_user.get(), entry_pass.get())
print("started bot")
root = tk.Tk()
entry_user = tk.Entry(root, bg="white", fg='black', bd=0)
#entry_user.insert(0, "Username")
#entry_user.bind("<Button-1>", del_value_user)
entry_user.pack(expand=True)
# Log in if the user presses the Enter key:
entry_user.bind("<Return>", create_bot)
entry_pass = tk.Entry(root, bg="white", fg='black', bd=0)
#entry_pass.insert(0, "Password")
#entry_pass.bind("<Button-1>", del_value_pass)
entry_pass.pack(expand=True)
# Log in if the user presses the Enter key:
entry_pass.bind("<Return>", create_bot)
button = tk.Button(root, text="Log in", command=create_bot)
button.pack()
root.mainloop()
Your code wasn't working because as soon as your code created the entries it tried to get the data out of them (which obviously is an empty string) and created the TwitterBot object. To make it work you have to give the user time to enter their details in the entries by adding a button/binding to the user pressing the Enter key.
I created a button and placed it at the bottom of the window. When you click the button it calls create_bot which creates the TwitterBot object.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import sys
import tkinter as tk
from tkinter import *
from tkmacosx import Button as button
class TwitterBot:
def __init__(self, username, password):
print("Username =", username, " Password =", password)
self.username = username
self.password = password
def open_br(self):
self.bot = webdriver.Firefox()
def end_br(self):
self.bot.quit()
def login(self):
bot = self.bot
bot.get("http://twitter.com/login/")
time.sleep(3)
email = bot.find_element_by_name("session[username_or_email]")
password = bot.find_element_by_name("session[password]")
email.clear()
password.clear()
email.send_keys(self.username)
password.send_keys(self.password)
password.send_keys(Keys.RETURN)
time.sleep(3)
def like_tweet(self, hashtag):
bot = self.bot
bot.get('https://twitter.com/search?q='+hashtag+'&src=typed_query')
time.sleep(3)
for i in range(1,8):
bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
time.sleep(2)
tweets = bot.find_elements_by_class_name('tweet')
tweetLinks = [i.get_attribute('href') for i in bot.find_elements_by_xpath("//a[#dir='auto']")]
filteredTweet = list(filter(lambda x: 'status' in x,tweetLinks))
print(filteredTweet)
for link in filteredTweet:
bot.get(link)
time.sleep(5)
if drop2_var.get() == "Retweet":
try:
bot.find_element_by_xpath("//div[#data-testid='retweet']").click()
bot.find_element_by_xpath("//div[#data-testid='retweetConfirm']").click()
time.sleep(3)
except Exception as ex:
time.sleep(10)
elif drop2_var.get() == "Likes":
bot.find_element_by_xpath("//div[#data-testid='like']").click()
time.sleep(3)
# def create_bot(event=None):
# sasha = TwitterBot(entry_user.get(), entry_pass.get())
# print("started bot")
sasha = TwitterBot("", "")
root = tk.Tk()
HEIGHT = 800
WIDTH = 400
#FUNCTIONS CLEARING ENTRY
def del_value(event): # note that you must include the event as an arg, even if you don't use it.
entry.delete(0, "end")
return None
def del_value_user(event): # note that you must include the event as an arg, even if you don't use it.
entry_user.delete(0, "end")
return None
def del_value_pass(event): # note that you must include the event as an arg, even if you don't use it.
entry_pass.delete(0, "end")
return None
def ex():
root.quit()
#PROGRAM SETTINGS
root.title("Social Bot")
root.minsize(400, 800)
#root.iconbitmap("/Users/sashakharoubi/Desktop/BOOTCAMP/Week 9/Day 2/image/logo.ico")
root.config(background="#66b3ff")
canvas = tk.Canvas(root, height= HEIGHT, width = WIDTH, bd=0, highlightthickness = 0)
canvas.pack()
# background_image = tk.PhotoImage(file = 'blue.png')
# background_label = tk.Label(root, image =background_image)
# background_label.place(x=0, y=0, relwidth=1, relheight=1)
#MAINFRAME
frame = tk.Frame(root, bg="#222f3e")
frame.place(relx = 0, rely = 0, relwidth = 1, relheight = 1)
#SUBPART FRAME
lower_frame = tk.Frame(root, bg="#E9E9E9", bd=0, highlightthickness = 0, relief="sunken")
#DROPDOWN MENU OPTIONS
OPTIONS = [
"Twitter",
"Instagram(not working)"
]
OPTIONS2 = [
"Likes",
"Retweet"
]
entry_txt = tk.Label(lower_frame, text="Welcome to Social Bot\n\nChoose an action to execute", font=("Montserrat", 15), bg="#E9E9E9", fg="black")
entry_txt.pack(expand = "yes")
#DROPDOWN MENU
drop_var = StringVar(lower_frame)
drop_var.set(OPTIONS[0])
drop2_var = StringVar(lower_frame)
drop2_var.set(OPTIONS2[0])
drop = OptionMenu(lower_frame, drop_var, *OPTIONS)
drop.config(fg="black")
drop.pack()
drop2 = OptionMenu(lower_frame, drop2_var, *OPTIONS2)
drop2.config(fg="black")
drop2.pack()
#ENTRIES
entry = tk.Entry(lower_frame, bg="white", fg='black', bd=0)
entry.insert(0, "-->Topic to like or retweet")
entry.bind("<Button-1>", del_value)
entry.pack(expand = "yes")
entry_user = tk.Entry(lower_frame, bg="white", fg='black', bd=0)
entry_user.insert(0, "----Type Your Username---")
entry_user.bind("<Button-1>", del_value_user)
entry_user.pack(expand = "yes")
#entry_user.bind("<Return>", create_bot)
entry_pass = tk.Entry(lower_frame, bg="white", fg='black', bd=0)
entry_pass.insert(0, "----Type Your Password---")
entry_pass.bind("<Button-1>", del_value_pass)
entry_pass.pack(expand = "yes")
#entry_pass.bind("<Return>", create_bot)
#BUTTONS
button_confirm = button(lower_frame, text="Confirm", bg="white", fg="black")
button_confirm.pack(pady=25, side = 'top')
button_open = button(lower_frame, text="Open Browser", bg="white", fg="black", command= sasha.open_br)
button_open.pack(pady=25, side = 'top')
button_log = button(lower_frame, text="LOG IN", bg='#54a0ff', fg="white", command =sasha.login, bd=0, highlightthickness = 0)
button_log.pack(pady=25, side = 'left')
button_launch = button(lower_frame, text="START", bg='#1dd1a1', fg="white", relief="flat", command = lambda: sasha.like_tweet(entry.get()), bd=0, highlightthickness = 0)
button_launch.pack(pady=25, side = 'right')
button_stop = button(lower_frame, text="STOP", bg="#ff6b6b", fg="white", command= sasha.end_br)
button_stop.pack(pady=25, side = 'bottom')
button_exit = button(lower_frame, text="Exit", bg ="white", fg="black", command= ex)
button_exit.pack(side = 'bottom')
lower_frame.place(relx = 0.1, rely = 0.1, relwidth=0.8, relheight=0.8)
#TITLE
label = tk.Label(frame, text="S O C I A L B O T", font=("Montserrat", 25), bg="white", fg="#222f3e")
label.pack(side="top", fill ="both")
root.mainloop()
v1 = browser.find_element_by_xpath("").text
try put .text at last of your code
then you can print or use v1 as a value
good day! here's my code:
import tkinter as tk
namemass =["dev", "Dev1"]
self.entry_name = ttk.Entry(self)
self.entry_name.place(x=200, y=50)
btn_cancel = ttk.Button(self, text="cancel", command=self.destroy)
btn_cancel.place(x=300, y=800)
btn_ok = ttk.Button(self, text="ok")
btn_ok.place(x=320, y=170)
so, i have 2 buttons and enter box. I want the program to get the text from the enter box and if namemass list have that inside, then exit. in console program i would code it like that:
name = input()
namemass = ["dev", "Dev1"]
if name in namemass:
import sys
sys.exit()
else:
..........
how to do it using tkinter? thank you in advance!
To fetch the current entry text, use the get method:
current_text = Entry.get()
in your example you can just:
from tkinter import *
import sys
def destroy():
name = entry_name.get()
if name in namemass:
sys.exit()
root = Tk()
namemass = ["dev", "Dev1"]
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok")
btn_ok.pack()
root.mainloop()
Much easier for Python 3.8, using Walrus. Just add the function for _ok. And add command in btn_ok.
from tkinter import *
import sys
namemass = ["dev", "Dev1"]
def destroy():
#sys.exit()
root.destroy()
def _ok():
if(name_in_list := entry_name.get()) in namemass:
sys.exit()
root = Tk()
entry_name = Entry(root)
entry_name.pack()
btn_cancel = Button(root, text="cancel", command=destroy)
btn_cancel.pack()
btn_ok = Button(root, text="ok", command=_ok)
btn_ok.pack()
root.mainloop()
I am working with tkinter library in python. I have a main window which has several buttons and when clicked those buttons a new window will popup which also has a button called cancel. I want to make that cancel button to all the windows.
I tried the following solution, which only closes the current window.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import datetime
import tkinter as tk
class AlertDialog:
def __init__(self):
self.invalidDiag = tk.Toplevel()
invalidInput = tk.Label(master=self.invalidDiag,
text='Error: Invalid Input').grid(row=1, column=1)
closeButton = tk.Button(master=self.invalidDiag,
text='Close',
command=self.invalidDiag.destroy).grid(row=2, column=1)
def start(self):
# self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
self.invalidDiag.wait_window()
class QuitDialog():
def __init__(self, ):
self.quitDialog = tk.Toplevel()
warnMessage = tk.Label(master=self.quitDialog,
text='Are you sure that you want to quit? ').grid(row=1, column=1)
cancelButton = tk.Button(master= self.quitDialog ,
text='Cancel',
command = self.quitALL).grid(row=2, column=1)
def start(self):
# self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
self.quitDialog.wait_window()
def quitALL(self):
self.quitDialog.destroy()
tc =TimeConverter()
tc.destroyit()
class TimeConverter:
def __init__(self):
self.mainWindow = tk.Tk()
self.mainWindow.title("Seconds Converter")
self.results = tk.StringVar()
self.inputSecs = tk.StringVar()
secLabel = tk.Label(master=self.mainWindow,
text="Seconds:").grid(row=0, sticky="W")
resultLabel = tk.Label(master=self.mainWindow,
text="Converted Time:\n(H:M:S)").grid(row=1, sticky="W")
calcResults = tk.Label(master=self.mainWindow,
background='light gray', width=20,
textvariable=self.results,
anchor="w").grid(row=1, column=1)
secEntry = tk.Entry(master=self.mainWindow,
width=24,
textvariable=self.inputSecs).grid(row=0, column=1)
calcButton = tk.Button(master=self.mainWindow,
text='Calculate',
command=self.SecondsToHours).grid(row=2,
column=0, sticky="w")
# quitButton = tk.Button(master=self.mainWindow,
# text='Quit',
# command=self.mainWindow.destroy).grid(row=2, column=1, sticky="E")
quitButton = tk.Button(master=self.mainWindow,
text='Quit',
command=self.showQuitDialog).grid(row=3, column=1, sticky="E")
def invalidInputEntered(self):
errorDiag = AlertDialog()
errorDiag.start()
def showQuitDialog(self):
quitdialog = QuitDialog()
quitdialog.start()
def startDisplay(self) -> None:
self.mainWindow.mainloop()
def destroyit(self):
self.mainWindow.destroy()
def SecondsToHours(self):
try:
inputseconds = int(self.inputSecs.get())
seconds = int(inputseconds % 60)
minutes = int(((inputseconds - seconds) / 60) % 60)
hours = int((((inputseconds - seconds) / 60) - minutes) / 60)
tempResults = str(hours) + ':' + str(minutes) + ':' + str(seconds)
self.results.set(tempResults)
return
except ValueError:
self.invalidInputEntered()
#self.showQuitDialog()
if __name__ == '__main__':
TimeConverter().startDisplay()
You are importing tkinter 2 times here. Onces with * and ones as tk.
Just use:
import tkinter as tk
this will help you avoid overriding anything that other libraries imports or having tkinter's functions overwritten by other imports.
You have a very unorthodox way of creating your tkinter app but if you wish to keep everything as is here is what you need to change:
Lets remove the cancel button from your quitDialog window and then add a yes and no button. This will server to allow you to either say yes to destroy all windows or to say no to only destroy the quitDialog window.
First we need to add an arguement to your QuitDialog class so we can pass the any window or frame we want to it.
So add the instance argument to your QuitDialog() class like below:
class QuitDialog():
def __init__(self, instance):
self.instance = instance
Now replace:
cancelButton = tk.Button(master= self.quitDialog ,
text='Cancel',
command = self.quitALL).grid(row=2, column=1)
With:
quitButton = tk.Button(master= self.quitDialog ,
text='Yes', command = self.quitALL).grid(row=2, column=1)
cancelButton = tk.Button(master= self.quitDialog,
text='No', command = lambda: self.quitDialog.destroy()).grid(row=2, column=2)
Then lets change your quitALL() method to:
def quitALL(self):
self.quitDialog.destroy()
self.instance.destroy()
This will use our instance argument to destroy a window we pass in.
Now change your showQuitDialog() method to:
def showQuitDialog(self):
quitdialog = QuitDialog(self.mainWindow)
quitdialog.start()
As you can see we are now passing the the tk window self.mainWindow to the QuitDialog class so we can decide on weather or not to close it.
Below is the copy past version of your code that should work as you need it to:
import tkinter as tk
from tkinter import ttk
import tkinter.messagebox
import datetime
class AlertDialog:
def __init__(self):
self.invalidDiag = tk.Toplevel()
invalidInput = tk.Label(master=self.invalidDiag,
text='Error: Invalid Input').grid(row=1, column=1)
closeButton = tk.Button(master=self.invalidDiag,
text='Close',
command=self.invalidDiag.destroy).grid(row=2, column=1)
def start(self):
# self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
self.invalidDiag.wait_window()
class QuitDialog():
def __init__(self, instance):
self.instance = instance
self.quitDialog = tk.Toplevel()
warnMessage = tk.Label(master=self.quitDialog,
text='Are you sure that you want to quit? ').grid(row=1, column=1, columnspan=2)
quitButton = tk.Button(master= self.quitDialog ,
text='Yes',
command = self.quitALL).grid(row=2, column=1)
cancelButton = tk.Button(master= self.quitDialog,
text='No',
command = lambda: self.quitDialog.destroy()).grid(row=2, column=2)
def start(self):
# self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
self.quitDialog.wait_window()
def quitALL(self):
self.quitDialog.destroy()
self.instance.destroy()
class TimeConverter:
def __init__(self):
self.mainWindow = tk.Tk()
self.mainWindow.title("Seconds Converter")
self.results = tk.StringVar()
self.inputSecs = tk.StringVar()
secLabel = tk.Label(master=self.mainWindow,
text="Seconds:").grid(row=0, sticky="W")
resultLabel = tk.Label(master=self.mainWindow,
text="Converted Time:\n(H:M:S)").grid(row=1, sticky="W")
calcResults = tk.Label(master=self.mainWindow,
background='light gray', width=20,
textvariable=self.results,
anchor="w").grid(row=1, column=1)
secEntry = tk.Entry(master=self.mainWindow,
width=24,
textvariable=self.inputSecs).grid(row=0, column=1)
calcButton = tk.Button(master=self.mainWindow,
text='Calculate',
command=self.SecondsToHours).grid(row=2,
column=0, sticky="w")
quitButton = tk.Button(master=self.mainWindow,
text='Quit',
command=self.showQuitDialog).grid(row=3, column=1, sticky="E")
def invalidInputEntered(self):
errorDiag = AlertDialog()
errorDiag.start()
def showQuitDialog(self):
quitdialog = QuitDialog(self.mainWindow)
quitdialog.start()
def startDisplay(self) -> None:
self.mainWindow.mainloop()
def destroyit(self):
self.mainWindow.destroy()
def SecondsToHours(self):
try:
inputseconds = int(self.inputSecs.get())
seconds = int(inputseconds % 60)
minutes = int(((inputseconds - seconds) / 60) % 60)
hours = int((((inputseconds - seconds) / 60) - minutes) / 60)
tempResults = str(hours) + ':' + str(minutes) + ':' + str(seconds)
self.results.set(tempResults)
return
except ValueError:
self.invalidInputEntered()
#self.showQuitDialog()
if __name__ == '__main__':
TimeConverter().startDisplay()
Interesting question. As I know, you can also use just quit() in order to quit from program by closing everything.
quit()
I made a separate file called clinic1.py for the other code and import it to the main page. Everything works fine however another window appears when I click save button on the add new item page.
When I place all the code on the main page that small window doesn't appear.
I cant find whats causing another window to appear when it's in a separate file.
This is my main page:
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
large_font = ('Verdana',12)
storedusername =['foo'] storedpass=['123'] storedretype=[]
list_of_users=storedusername
list_of_passwords=storedpass
def all_clinic_frames(event):
combo_clinic=combo.get()
if combo_clinic == 'Clinic 1':
enter()
root = Tk()
root.geometry('800x600')
root.title('CSSD')
topFrame=Frame(root,width=800,height=100,padx=310)
area=Label(topFrame,text='CSSD')
area.config(font=("Courier", 50))
frame=Frame(root,highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100, bd= 0)
frame.place(relx=.5, rely=.5, anchor="center")
username = Label(frame, text='User Name') username.config(font='Arial',width=15) password = Label(frame, text='Password') password.config(font='Arial',width=15) enteruser = Entry(frame, textvariable=StringVar(),font=large_font) enterpass = Entry(frame, show='*', textvariable=StringVar(),font=large_font)
combo_choice=StringVar()
combo=ttk.Combobox(frame,textvariable=combo_choice)
combo['values']=('Clinic 1')
combo.state(['readonly'])
combo.grid(row=0,sticky=NW)
combo.set('Choose Area...')
combo.bind('<<ComboboxSelected>>',all_clinic_frames)
topFrame.grid(row=0,sticky=N) topFrame.grid_propagate(False) area.grid(row=0,column=1,sticky=N) username.grid(row=1, sticky=E) enteruser.grid(row=1, column=1) password.grid(row=2, sticky=E) enterpass.grid(row=2, column=1)
def valid():
usernameRight=enteruser.get()
passwordRight=enterpass.get()
while True:
try:
if (usernameRight==list_of_users[0]) and (passwordRight==list_of_passwords[0]):
import clinic1
clinic1.main_page()
quit()
break
except IndexError:
invalid = Label(frame, text='User name or Password is incorrect!', fg='red')
invalid.grid(row=3, columnspan=2)
break
def enter():
register = Button(frame, text='Sign In',relief=RAISED,fg='white',bg='red',command=valid)
register.grid(row=3,column=1,ipadx=15,sticky=E)
def quit():
root.destroy()
And this is the second file that I imported in the main page which i saved as clinic1.py
from tkinter import*
import tkinter.messagebox
newInstList=[]
def addItem(event=None):
global back_add,quantityentry,itemEntry,itemEntry1,quantityentry1
itemFrameTop=Frame(root, width=800,height=100,bg='pink')
itemFrameTop.grid_propagate(False)
itemFrameTop.grid(row=0)
area1_item = Label(itemFrameTop, text='CSSD', pady=5,padx=230)
area1_item.config(font=("Courier", 30))
area1_item.grid_propagate(False)
area1_item.grid(row=0,column=1,sticky=NE)
clinic_1 = Label(itemFrameTop, text='Clinic 1', bg='red', fg='white', bd=5)
clinic_1.config(font=("Courier", 15))
clinic_1.grid_propagate(False)
clinic_1.grid(row=1, sticky=W,padx=10)
itemFrameMid=Frame(root,width=700,height=600,bg='blue')
itemFrameMid.grid_propagate(False)
itemFrameMid.grid(row=1)
itemname=Label(itemFrameMid,text='Item name:')
itemname.config(font=('Arial,15'))
itemname.grid_propagate(False)
itemname.grid(row=1,sticky=E)
quantity=Label(itemFrameMid,text='Qty:')
quantity.config(font=('Arial,15'))
quantity.grid_propagate(False)
quantity.grid(row=1,column=3, sticky=E,padx=10)
itemEntry=Entry(itemFrameMid)
itemEntry.config(font=('Arial,15'))
itemEntry.grid(row=1,column=1,sticky=EW,padx=30,pady=10)
itemEntry1 = Entry(itemFrameMid)
itemEntry1.config(font=('Arial,15'))
itemEntry1.grid(row=2, column=1)
quantityentry=Entry(itemFrameMid,width=5)
quantityentry.config(font=('Arial',15))
quantityentry.grid(row=1, column=4)
quantityentry1 = Entry(itemFrameMid, width=5)
quantityentry1.config(font=('Arial', 15))
quantityentry1.grid(row=2, column=4,padx=10)
"""When I click save button another small window appears"""
okbutton = Button(itemFrameMid, text='Save', command=saveCheck)
okbutton.config(font=('Arial', 12))
okbutton.grid(row=3, column=4, padx=15)
back_add = Label(itemFrameTop, text='Back')
back_add.config(font=('Courier,15'))
back_add.grid(row=0, sticky=W, padx=30)
back_add.bind('<Button-1>', main_page)
back_add.bind('<Enter>', red_text_back1)
back_add.bind('<Leave>', black_text_back1)
def saveCheck():
saveQuestion=tkinter.messagebox.askquestion('CSSD', 'Are you sure you want to save?')
if saveQuestion == 'yes':
newInstList.append(itemEntry.get())
newInstList.append(quantityentry.get())
newInstList.append(itemEntry1.get())
newInstList.append(quantityentry1.get())
print(newInstList)
main_page()
elif saveQuestion == 'no':
pass
def red_text_back1(event=None):
back_add.config(fg='red')
def black_text_back1(event=None):
back_add.config(fg='black')
def red_text_add(event=None):
addnew.config(fg='red')
def black_text_add(event=None):
addnew.config(fg='black')
def main_page(event=None):
global addnew,usedInst,logOut
frame1 = Frame(root, width=800, height=100,bg='pink')
frame1.grid(row=0, column=0, sticky="nsew")
frame1.grid_propagate(False)
midframe1=Frame(root,width=800,height=600)
midframe1.grid_propagate(False)
midframe1.grid(row=1)
area1 = Label(frame1, text='CSSD',pady=5,padx=350)
area1.config(font=("Courier", 30))
area1.grid(row=0)
clinic1=Label(frame1,text='Clinic 1',bg='red',fg='white',bd=5)
clinic1.config(font=("Courier", 15))
clinic1.grid_propagate(False)
clinic1.grid(row=1,sticky=W,padx=10)
addnew=Label(midframe1,text='+ Add new item')
addnew.config(font=('Arial',15))
addnew.grid(row=2,column=1,sticky=E,ipadx=50)
addnew.bind('<Button-1>', addItem)
addnew.bind('<Enter>', red_text_add)
addnew.bind('<Leave>', black_text_add)
root = Tk()
root.geometry('800x600')
Both files have this line of code:
root = Tk()
Each time you do that, you get another root window. A tkinter application needs to have exactly one instance of Tk running at a time.
You need to remove the last two lines from clinic1.py. You will also need to pass in the reference to root to any methods from clinic1.py that need it.
First file.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
large_font = ('Verdana',12)
storedusername =['foo']
storedpass=['123']
storedretype=[]
list_of_users=storedusername
list_of_passwords=storedpass
def all_clinic_frames(event):
combo_clinic=combo.get()
if combo_clinic == 'Clinic 1':
enter()
root = Tk()
root.geometry('800x600')
root.title('CSSD')
topFrame=Frame(root,width=800,height=100,padx=310)
area=Label(topFrame,text='CSSD')
area.config(font=("Courier", 50))
frame=Frame(root,highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100, bd= 0)
frame.place(relx=.5, rely=.5, anchor="center")
myvar=StringVar()
username = Label(frame, text='User Name')
username.config(font='Arial',width=15)
password = Label(frame, text='Password')
password.config(font='Arial',width=15)
enteruser = Entry(frame, textvariable=myvar, font=large_font)
pass1=StringVar()
enterpass = Entry(frame, show='*', textvariable=pass1, font=large_font)
combo_choice=StringVar()
combo=ttk.Combobox(frame,textvariable=combo_choice)
combo['values']=[('Clinic 1')]
combo.state(['readonly'])
combo.grid(row=0,sticky=NW)
combo.set('Choose Area...')
combo.bind('<<ComboboxSelected>>',all_clinic_frames)
topFrame.grid(row=0,sticky=N)
topFrame.grid_propagate(False)
area.grid(row=0,column=1,sticky=N)
username.grid(row=1, sticky=E)
enteruser.grid(row=1, column=1)
password.grid(row=2, sticky=E)
enterpass.grid(row=2, column=1)
def valid():
usernameRight=enteruser.get()
passwordRight=enterpass.get()
while True:
try:
if (usernameRight==list_of_users[0]) and (passwordRight==list_of_passwords[0]):
import clinic1
clinic1.main_page(root)
# quit()
break
except IndexError:
invalid = Label(frame, text='User name or Password is incorrect!', fg='red')
invalid.grid(row=3, columnspan=2)
break
def enter():
register = Button(frame, text='Sign In',relief=RAISED,fg='white',bg='red',command=valid)
register.grid(row=3,column=1,ipadx=15,sticky=E)
def quit():
root.destroy()
root.mainloop()
clinic1.py
from tkinter import*
import tkinter.messagebox
newInstList=[]
def addItem(root, event=None):
global back_add,quantityentry,itemEntry,itemEntry1,quantityentry1
if event is None:
event = Event()
itemFrameTop=Frame(root, width=800, height=100, bg='pink')
itemFrameTop.grid_propagate(False)
itemFrameTop.grid(row=0)
area1_item = Label(itemFrameTop, text='CSSD', pady=5,padx=230)
area1_item.config(font=("Courier", 30))
area1_item.grid_propagate(False)
area1_item.grid(row=0,column=1,sticky=NE)
clinic_1 = Label(itemFrameTop, text='Clinic 1', bg='red', fg='white', bd=5)
clinic_1.config(font=("Courier", 15))
clinic_1.grid_propagate(False)
clinic_1.grid(row=1, sticky=W,padx=10)
itemFrameMid=Frame(root,width=700,height=600,bg='blue')
itemFrameMid.grid_propagate(False)
itemFrameMid.grid(row=1)
itemname=Label(itemFrameMid,text='Item name:')
itemname.config(font=('Arial,15'))
itemname.grid_propagate(False)
itemname.grid(row=1,sticky=E)
quantity=Label(itemFrameMid,text='Qty:')
quantity.config(font=('Arial,15'))
quantity.grid_propagate(False)
quantity.grid(row=1,column=3, sticky=E,padx=10)
itemEntry=Entry(itemFrameMid)
itemEntry.config(font=('Arial,15'))
itemEntry.grid(row=1,column=1,sticky=EW,padx=30,pady=10)
itemEntry1 = Entry(itemFrameMid)
itemEntry1.config(font=('Arial,15'))
itemEntry1.grid(row=2, column=1)
quantityentry=Entry(itemFrameMid,width=5)
quantityentry.config(font=('Arial',15))
quantityentry.grid(row=1, column=4)
quantityentry1 = Entry(itemFrameMid, width=5)
quantityentry1.config(font=('Arial', 15))
quantityentry1.grid(row=2, column=4,padx=10)
"""When I click save button another small window appears"""
okbutton = Button(itemFrameMid, text='Save', command=lambda: saveCheck(root))
okbutton.config(font=('Arial', 12))
okbutton.grid(row=3, column=4, padx=15)
back_add = Label(itemFrameTop, text='Back')
back_add.config(font=('Courier,15'))
back_add.grid(row=0, sticky=W, padx=30)
back_add.bind('<Button-1>', main_page)
back_add.bind('<Enter>', red_text_back1)
back_add.bind('<Leave>', black_text_back1)
def saveCheck(root):
saveQuestion=tkinter.messagebox.askquestion('CSSD', 'Are you sure you want to save?')
if saveQuestion == 'yes':
newInstList.append(itemEntry.get())
newInstList.append(quantityentry.get())
newInstList.append(itemEntry1.get())
newInstList.append(quantityentry1.get())
print(newInstList)
main_page(root)
elif saveQuestion == 'no':
pass
def red_text_back1(event=None):
back_add.config(fg='red')
def black_text_back1(event=None):
back_add.config(fg='black')
def red_text_add(event=None):
addnew.config(fg='red')
def black_text_add(event=None):
addnew.config(fg='black')
def main_page(root):
global addnew,usedInst,logOut
frame1 = Frame(root, width=800, height=100,bg='pink')
frame1.grid(row=0, column=0, sticky="nsew")
frame1.grid_propagate(False)
midframe1=Frame(root,width=800,height=600)
midframe1.grid_propagate(False)
midframe1.grid(row=1)
area1 = Label(frame1, text='CSSD',pady=5,padx=350)
area1.config(font=("Courier", 30))
area1.grid(row=0)
clinic1=Label(frame1,text='Clinic 1',bg='red',fg='white',bd=5)
clinic1.config(font=("Courier", 15))
clinic1.grid_propagate(False)
clinic1.grid(row=1,sticky=W,padx=10)
addnew=Button(midframe1,text='+ Add new item', font=('Arial', 15), command=lambda: addItem(root))
addnew.grid(row=2,column=1,sticky=E,ipadx=50)
# addnew.bind('<Button-1>', lambda r=root: addItem(r))
addnew.bind('<Enter>', red_text_add)
addnew.bind('<Leave>', black_text_add)
I'm building a python GUI and there I got 2 text boxes.
I want to create a submit button that will take the data from those 2 text boxes and send them to start(save_place, website_url) function.
This is what I got so far:
from Tkinter import *
def start(save_place, website_url):
#something
app = Tk()
top_app = Frame(app)
top_app.pack()
save_location = Entry(top_app, width=20)
url = Entry(top_app, width=20)
save_location.grid(sticky=W, row=0)
url.grid(sticky=W, row=1)
save_place = save_location.get("1.0", END)
website_url = url.get("1.0", END)
button_start = Button(top_app, text="Start", fg="green", command=start(save_place,website_url))
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
I also tried this:
from Tkinter import *
def start():
save_place = save_loc.get()
website_url = urls.get()
print (save_place + " " + website_url)
app = Tk()
top_app = Frame(app)
top_app.pack()
save_loc = StringVar()
save_location = Entry(top_app, textvariable=save_loc, width=85)
urls = StringVar()
url = Entry(top_app, textvariable=urls, width=85)
button_start = Button(top_app, text="Start", fg="green", command=start)
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
And it didn't work.
How can I make this script send the inputs in the text boxes to the function?
Thanks to all the helpers :)
As mentioned in the previous response "about how to call a function", you just put command = start and put save_place = save_location.get()
in start function, however you can use save_location = Entry(top_app, width=20), so the total prg:
from Tkinter import *
def start():
#something
save_place = save_location.get()
website_url = url.get()
print save_place,website_url
app = Tk()
top_app = Frame(app)
top_app.pack()
save_location = Entry(top_app, width=20)
url = Entry(top_app, width=20)
save_location.grid(sticky=W, row=0)
url.grid(sticky=W, row=1)
button_start = Button(top_app, text="Start", fg="green", command=start)
button_start.grid(sticky=W, row=2, pady=20)
app.mainloop()
command=start(save_place,website_url) doesn't do what you think its doing. It's assigning the result of the function call to the command. (Which is probably None). Bind your Entry boxes to StringVar like:
location = StringVar()
Entry(top_app, textvariable=location, width=20)
Then you assign the function call to the command parameter using command = start. Inside the function you can access the value in the Entry using location.get(). To set the value use the corresponding method location.set(value)