I am trying to make a GUI that will write to a CSV file. I want whatever I put into the entry boxes to write to a corresponding cell.
An example of entries I want to see in the CSV is:
vlan 8
192.168.1.1 255.255.255.0
fa2/0/1
however, when I open the data1.csv it writes:
PY_VAR0
PY_VAR1
PY_VAR2
Here is the python code I wrote:
import csv
from tkinter import *
root = Tk()
root.geometry('300x300')
root.title("Cisco-Oneport")
photo = PhotoImage(file = "Logo.PNG")
root.iconphoto(False, photo)
def info():
list_of_lists = [[f'{vlan}',],
[f'{ip}',],
[f'{port}',]]
with open('data1.csv', 'w', newline='') as f:
writer = csv.writer(f, delimiter=';')
for sublist in list_of_lists:
writer.writerow(sublist)
entry1_text = Label(text = "Type Vlan Number * ",)
entry2_text = Label(text = "Type IP Number and Subnet * ",)
entry3_text = Label(text = "Type in Fast Port * ",)
entry1_text.place(x = 15, y = 30)
entry2_text.place(x = 15, y = 90)
entry3_text.place(x = 15, y = 150)
vlan = StringVar()
ip = StringVar()
port = StringVar()
vlan_entry = Entry(textvariable = vlan, width = "10")
ip_entry = Entry(textvariable = ip, width = "30")
port_entry = Entry(textvariable = port, width = "10")
vlan_entry.place(x = 15, y = 60)
ip_entry.place(x = 15, y = 120)
port_entry.place(x = 15, y = 180)
register = Button(root,text = "Run", width = "10", height = "2", command = info, bg = "lightgreen")
register.place(x = 15, y = 240)
root.mainloop()
How do I get the desired inputs? I'm pretty new to light GUI coding.
The .csv file is showing the tcl/tk names for the StringVars. Use .get() to get the values. The Labels and Entries were created without a containing object so I was seeing one GUI with the Text and a separate one with the run button.
It's easier to answer questions where the code can be copied and run in a console. Therefore it's better to remove things like icons which use files that won't exist on another PC.
import csv
from tkinter import *
root = Tk()
root.geometry('300x300')
root.title("Cisco-Oneport")
# Removed icon as I cant access the file
# Use .get() to get the values of the StringVars, not the names of the StringVars
def info():
list_of_lists = [[f'{vlan.get()}',],
[f'{ip.get()}',],
[f'{port.get()}',]]
with open('data1.csv', 'w', newline='') as f:
writer = csv.writer(f, delimiter=';')
for sublist in list_of_lists:
writer.writerow(sublist)
# Add root to put the all the objects in the same GUI
entry1_text = Label(root, text = "Type Vlan Number * ",)
entry2_text = Label(root, text = "Type IP Number and Subnet * ",)
entry3_text = Label(root, text = "Type in Fast Port * ",)
entry1_text.place(x = 15, y = 30)
entry2_text.place(x = 15, y = 90)
entry3_text.place(x = 15, y = 150)
vlan = StringVar()
ip = StringVar()
port = StringVar()
# Add root to put the all the objects in the same GUI
vlan_entry = Entry(root, textvariable = vlan, width = "10")
ip_entry = Entry(root, textvariable = ip, width = "30")
port_entry = Entry(root, textvariable = port, width = "10")
vlan_entry.place(x = 15, y = 60)
ip_entry.place(x = 15, y = 120)
port_entry.place(x = 15, y = 180)
#
register = Button(root,text = "Run", width = "10", height = "2", command = info, bg = "lightgreen")
register.place(x = 15, y = 240)
root.mainloop()
Related
I'm working on a simple registration phase for a password scheme, but I can't seem to get the value in the combobox as an integer as it keeps giving ValueError: invalid literal for int() with base 10: ''. I've tried many methods but they don't seem to work. Additionally, I want to store the data in the entry and comboboxes for my next window, but it keeps registering as ValueError: '' is not in list.
The code:
import tkinter as tk
from tkinter import *
import random
from tkinter import messagebox
from tkinter import ttk
from tkinter.ttk import Combobox
root = tk.Tk()
root.geometry("375x130")
var = tk.StringVar()
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lbl = tk.Label(root, text = "Your password must have 7 to 15 characters with \nat least 1 number, 1 uppercase and 1 lowercase letter. ")
lbl1 = tk.Label(root, text = "Choose your password: ")
lbl2 = tk.Label(root, text = "n")
lbl3 = tk.Label(root, text = "y")
entry1 = tk.Entry(root)
combo1 = Combobox(root, values = data, state = "readonly")
combo2 = Combobox(root, values = data, state = "readonly")
lbl.place(x = 10, y = 0)
lbl1.place(x = 10, y = 35)
lbl2.place(x = 10, y = 60)
lbl3.place(x = 10, y = 85)
entry1.place(x = 155, y = 35)
combo1.place(x = 25, y = 60)
combo2.place(x = 25, y = 85)
pw = entry1.get()
n = combo1.get()
y = combo2.get()
root.title('Registration')
done_button = tk.Button(root, text = "Done", command = root.destroy, width = 5)
done_button.place(x = 205, y = 80)
root.mainloop()
password = str(pw)
n = int(data.index(n)) - 1
y = int(data.index(y)) - 1
When the following lines are executed:
pw = entry1.get()
n = combo1.get()
y = combo2.get()
The entry box and the two comboboxes are just created, so nothing is input in the entry box and nothing is selected in the two comboboxes.
You need to do it inside a function triggered by the "Done" button:
...
# function called by "Done" button
def done():
pw = entry1.get()
n = int(combo1.get()) # convert selection to integer
y = int(combo2.get()) # convert selection to integer
print(f"{pw=}, {n=}, {y=}")
n = data.index(n) - 1
y = data.index(y) - 1
print(f"{n=}, {y=}")
root.destroy()
root.title('Registration')
done_button = tk.Button(root, text = "Done", command = done, width = 5)
done_button.place(x = 205, y = 80)
root.mainloop()
Output in console:
pw='hello', n=4, y=9
n=2, y=7
There are a couple of issues with your code:
Firstly, you need to bind the combobox change events with a function of some sort
The combobox returns a string of the number selected - which needs conversion
I am not sure what you aimed to do with n and y - but I kept the formula you used.
Fix these, and the combobox issues resolve.
See code below:
Code:
import tkinter as tk
from tkinter import *
import random
from tkinter import messagebox
from tkinter import ttk
from tkinter.ttk import Combobox
def combo_n_changed(event):
n = combo1.get()
n = int(data.index(int(n))) - 1
print("n=",n)
def combo_y_changed(event):
y = combo2.get()
y = int(data.index(int(y))) - 1
print("y=",y)
root = tk.Tk()
root.geometry("375x130")
var = tk.StringVar()
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lbl = tk.Label(root, text = "Your password must have 7 to 15 characters with \nat least 1 number, 1 uppercase and 1 lowercase letter. ")
lbl1 = tk.Label(root, text = "Choose your password: ")
lbl2 = tk.Label(root, text = "n")
lbl3 = tk.Label(root, text = "y")
entry1 = tk.Entry(root)
combo1 = Combobox(root, values = data, state = "readonly")
combo2 = Combobox(root, values = data, state = "readonly")
lbl.place(x = 10, y = 0)
lbl1.place(x = 10, y = 35)
lbl2.place(x = 10, y = 60)
lbl3.place(x = 10, y = 85)
entry1.place(x = 155, y = 35)
combo1.place(x = 25, y = 60)
combo2.place(x = 25, y = 85)
pw = entry1.get()
combo1.bind('<<ComboboxSelected>>', combo_n_changed)
combo2.bind('<<ComboboxSelected>>', combo_y_changed)
root.title('Registration')
done_button = tk.Button(root, text = "Done", command = root.destroy, width = 5)
done_button.place(x = 205, y = 80)
root.mainloop()
I entered the information as per the image below:
Output:
n= 1
y= 2
i am making a sign up page and im trying to store the email the user entered to a text file but it doesnt seem to work it stores ".!toplevel.!entrywrite" instead of user input. i am new to this python and tkinter so i dont really know what to do, the code is a little bit long sorry about that.
Any help will be appreciated. Thank you
from tkinter import*
from PIL import Image, ImageTk
import tkinter as tk
root = Tk()
root.geometry('670x466')
class Goode_brothers:
def __init__(self, parent):
myFrame = Frame(parent)
myFrame.pack()
self.load = Image.open('new-dip-project\\food.jpg')
self.render = ImageTk.PhotoImage(self.load)
self.img = Label(parent, image = self.render)
self.img.place(x = -26, y =0)
self.img_login = PhotoImage(file = 'new-dip-project\\button (3).png')
self.b1 = Button(parent,image = self.img_login,bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b1.place(x = 275, y = 310)
self.img_register = PhotoImage(file = 'new-dip-project\\register.png')
self.b2 = Button(parent,image = self.img_register, command = self.openNewWindow, bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b2.place(x = 265, y = 400)
self.canvas = Canvas(parent, width = 400, height = 120)
self.canvas.pack()
self.img4 = ImageTk.PhotoImage(Image.open('new-dip-project\\goode.png'))
self.canvas.create_image(20, 20, anchor=NW, image=self.img4)
self.email = Entry(parent).place(x = 340, y = 180)
self.password = Entry(parent).place(x = 340, y = 250)
self.img_label = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(parent, image = self.img_label, text = "Email:", bg = '#3c3a3b').place(x = 197,y = 178)
self.img_label_pass = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(parent, image = self.img_label_pass, text = "Password:", bg = '#3c3a3b').place(x = 177,y = 245)
def create_pass(self):
self.password_length = Label(self.root2, text = '')
self.password_length.place(x = 80, y = 140)
self.pass_word = str(self.password2.get()) #this code is getting the users input from the password entry box
if len(self.pass_word) >= 8: #if the characters gotten from the pasword entry is less than 8, an erorr message will appear
self.registered = Label(self.root2, text = 'You have successfully registered, this window will now automatically close', font=("open sans", "8"))
self.registered.place(x = 80, y = 140)
self.root2.after(4000, self.root2.destroy)
else:
self.password_length.configure(text="""Your password must be atleast eight characters long. Please try again""", font=("open sans", "8"))
def save_info(self):
self.email_reg = str(self.email2.get())
print(self.email2)
file = open('emails.txt', 'w')
file.write(str(self.email2))
def create_email(self):
self.username_length = Label(self.root2, text = '', font = '40')
self.username_length.place(x = 165, y = 140)
self.email_reg = str(self.email2.get())
if len(self.email_reg) >= 1: #if user has inputted a letter or number it will allow it to go to the next function
self.save_info()
self.create_pass()
self.username_length.destroy()
else:
self.username_length.configure(text='Please enter your username or password', font=("open sans", "8"))
self.username_length.after(3000, self.username_length.destroy)
def openNewWindow(self):
# Toplevel object which will
# be treated as a new window
self.root2 = Toplevel(root)
# sets the title of the
# Toplevel widget
self.root2.title("New Window")
# sets the geometry of toplevel
self.root2.geometry("500x300")
self.load2 = Image.open('new-dip-project\\registerscreen3.jpg')
self.render2 = ImageTk.PhotoImage(self.load2)
self.img2 = Label(self.root2, image = self.render2)
self.img2.place(x = -2, y =0)
self.img_label2 = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(self.root2, image = self.img_label, bg = '#292929').place(x = 130,y = 102)
self.img_label_pass2 = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(self.root2, image = self.img_label_pass, bg = '#292929').place(x = 120,y = 173)
self.email2 = Entry(self.root2)
self.email2.place(x = 280, y = 104)
self.password2 = Entry(self.root2)
self.password2.place(x = 280, y = 180)
self.img_register2 = PhotoImage(file = 'new-dip-project\\register.png')
self.b3 = Button(self.root2,image = self.img_register2, command = self.create_email, bd = 0, bg = '#0d0d0d', activebackground = '#0d0d0d')
self.b3.place(x = 180, y = 250)
self.img_reg2 = PhotoImage(file = 'new-dip-project\\regtitle.png')
self.name9 = Label(self.root2, image = self.img_reg2, bg = '#131313')
self.name9.place(x = 109, y = 10)
if __name__ == "__main__":
e = Goode_brothers(root)
root.title('Goode brothers')
root.mainloop()
Using var = StringVar() to set option textvariable - var when initialize Entry, and get content of Entry by var.get().
example Code
from tkinter import *
def on_click():
print(entry_text.get())
root = Tk()
font = ("Courier New", 32)
entry_text = StringVar()
entry = Entry(root, textvariable=entry_text, font=font)
entry.place(x=0, y=0)
button = Button(root, text='Check', command=on_click, font= font)
button.place(x=0, y=64)
root.mainloop()
Following statement will get value None for self.email
self.email = Entry(parent).place(x = 340, y = 180)
should be
self.email = Entry(parent)
self.email.place(x = 340, y = 180)
My program stops working after successfully running the two exes. here is the code:
from tkinter import *
import os
root = Tk()
root.geometry('350x150')
root.title("hurler")
photo = PhotoImage(file = "Logo_Image.png")
root.iconphoto(False, photo)
entry_text = Label(text = "Number of posts you wish to automate (between 1-12) * ")
entry_text.place(x = 15, y = 10)
num = StringVar()
time_entry = Entry(textvariable = num, width = "10")
time_entry.place(x = 15, y = 40)
def action():
global num
num = num.get()
if num == '1':
os.startfile('.\\hurl\\hurl.exe')
# exit()
if num == '2':
os.startfile('.\\hurl\\hurl.exe')
os.startfile('.\\hurl2\\hurl.exe')
# exit()
num = StringVar()
register = Button(root,text = "Make", width = "10", height = "2", command = action, bg = "lightblue")
register.place(x = 15, y = 70)
root.mainloop()
hurl takes in text entries and then runs a web driver exe after pressing the Post button. Heres a sample block from code from hurl:
from tkinter import *
import os
from time import sleep
root = Tk()
root.geometry('600x600')
root.title("hurl")
photo = PhotoImage(file = "Logo_Image.png")
root.iconphoto(False, photo)
def save_post():
emailE = email_in.get()
file1 = open ("user.txt", "w")
file1.write(emailE)
file1.close()
passE = pass_in.get()
file2 = open ('pass.txt', 'w')
file2.write(passE)
file2.close()
entry1_text = Label(text = "Email * ",)
entry2_text = Label(text = "Password * ",)
entry1_text.place(x = 15, y = 70)
entry2_text.place(x = 15, y = 130)
email_in = StringVar()
pass_in = StringVar()
email_entry = Entry(textvariable = email_in, width = "30")
pass_entry = Entry(textvariable = pass_in, width = "30")
def app():
os.system(".\Auto_Post_With_Photo.exe")
def everything():
save_post()
app()
register = Button(root,text = "Post", width = "10", height = "2", command = everything, bg = "lightblue")
register.place(x = 15, y = 380)
root.mainloop()
I'm hoping I don't need to show the last program to get an answer to the issue. The Issue I'm having is that the program runs perfectly until the button is pressed, and then the hurls exes crash.
But if I click on the two hurl.exe with my mouse and not this 3rd program pressing the post button won't crash.
Any ideas to fix this issue? Also, it's not due to the 'exit()s', it does the same thing with or without them. :)
The function of this code is that it displays the list of records in a database with one of the fields being a button. When this button is clicked it brings the user to a new frame which displays the account information for that record.
The record information is displayed in the Record class as dat[0] and dat[1] and I have had problems with initializing this in the second class, I do not know how I would get this information to appear on the second screen.
Thanks for any help.
from tkinter import *
import sqlite3
import AddAccount
import RemoveAccount
import LogOnLib
import LoginMenu
import TrainerAccounts
class Records(object):
def __init__(self, window):
self.window = window
window.state("zoomed")
self.window.title('Trainer Accounts')
window.update_idletasks()
h = self.window.winfo_height()
w = self.window.winfo_width()
Center_h = h/2
Center_w = w/2
self.FrameRecords = Frame(window, bg = "PaleTurquoise1")
self.FrameRecords.place(x = Center_w , y = Center_h, anchor = "center", width = 1024, height = 300)
self.btn_Back = Button(self.FrameRecords, text = "Back", bg = "PaleTurquoise1", font =("Arial", "16"), command = self.Back, width = 20)
self.btn_Back.grid(row = 1, column = 4, columnspan = 5)
self.connection = sqlite3.connect(r"E:\Program\Accounts.db")
self.cur = self.connection.cursor()
self.btn_TrainerID = Label(self.FrameRecords, text = "Trainer ID", bg = "PaleTurquoise1", font =("Arial", "16"), width = 20)
self.btn_TrainerID.grid(row = 0, column = 1, columnspan = 1)
self.NameLabel = Label(self.FrameRecords, text = "Name", bg = "PaleTurquoise1", font =("Arial", "16"), width = 20)
self.NameLabel.grid(row=0, column=0)
self.showallrecords()
def showallrecords(self):
Data = self.readfromdatabase()
for index, dat in enumerate(Data):
self.row1 = Button(self.FrameRecords, text=dat[0],font =("Arial", "16"), command = self.account).grid(row=index+1, column=0)
self.row2 = Label(self.FrameRecords, text=dat[1],font =("Arial", "16")).grid(row=index+1, column=1)
def readfromdatabase(self):
self.cur.execute("SELECT * FROM Trainers")
return self.cur.fetchall()
self.btn_TrainerID = self.row1
self.NameLabel = self.row2
def Back(self):
self.FrameRecords.place_forget()
GUI = LoginMenu.Logged(self.window)
def account(self):
self.FrameRecords.place_forget()
GUI = TrainerAccounts.TrainerInfo(self.window, Records)
##########################################################################################################################################################################################
class TrainerInfo(Records):
def __init__(self, window, Records):
self.window = window
window.state("zoomed")
self.window.title('CHANGEEEE')
window.update_idletasks()
h = self.window.winfo_height()
w = self.window.winfo_width()
Center_h = h/2
Center_w = w/2
self.FrameTrainerInfo = Frame(window, bg = "PaleTurquoise1")
self.FrameTrainerInfo.place(x = Center_w , y = Center_h, anchor = "center", width = 1024, height = 300)
self.connection = sqlite3.connect(r"E:\Program\Accounts.db")
self.cur = self.connection.cursor()
self.showrecord()
def showrecord(self):
Data = self.Information()
for index, dat in enumerate(Data):
Label(self.FrameTrainerInfo, text=self.row1,font =("Arial", "16")).grid(row=index+1, column=0)
Label(self.FrameTrainerInfo, text=self.row2,font =("Arial", "16")).grid(row=index+1, column=1)
def Information(self):
self.cur.execute("SELECT * FROM Trainers WHERE row1 = '" + row1 + "'" + "AND row2 = '" + row2 + "'")
return self.cur.self.all()
Have you tried merging the two classes together ?
if you can push values from database you only need make a .insert on Entrybox
maybe like this
tkEntry = Entry( master)
tkEntry.pack() # .grid or .place, don't make this in obj create
tkEntry.insert( 0, dat[0] ) # 0 is the index and dat[0] is your value
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 6 years ago.
ive currently been trying to build a GUI application in Tkinter that takes user input from an Entry and subsiquently populate a drop down menu. The probelm is that the OptionMenu keeps throwing:
Traceback (most recent call last):
File "C:/Python34/food2GUIree.py", line 70, in <module>
mealOneButton = Button(root, text = "query database", command = GetEntry(mealOneString))
File "C:/Python34/food2GUIree.py", line 68, in GetEntry
meal = OptionMenu(root, '', *getMeal).pack()
TypeError: __init__() missing 1 required positional argument: 'value'
when i replace getMeal in:
def GetEntry(x):
formatted = x.get().split()##gets the entry and forms a list
getMeal = CsvLoadSearch(u, formatted)
meal = OptionMenu(root, '', *getMeal).pack()
with list = [1,2,3,4] or any other list it works fine. why is this?
bellow is the complete program:
from tkinter import *
from tkinter import ttk
import csv
import os
u = "C:\\Users\\luke daniels\\Documents\\fooddata.csv"
"""
Loads csv and compares elements from foodList with current row.
returns a list of rows that match elements in foodList.
"""
def CsvLoadSearch(u, foodList):
results = []
inputfile = open(u)
for row in csv.reader(inputfile):
for food in foodList:
if food in row[0]:
results.append(row[0])
##print(row)
return results
root = Tk()
root.title("MacroCalc")
caloriesAim = StringVar()
protien = StringVar()
fat = StringVar()
carbs = StringVar()
mealOneString = StringVar()
mealTwoString = StringVar()
mealThreeString = StringVar()
mealFourString = StringVar()
mealFiveString = StringVar()
mealSixString = StringVar()
mealOneKeyword = Entry(root, textvariable = mealOneString)
mealTwoKeyword = Entry(root, textvariable = mealTwoString)
mealThreeKeyword = Entry(root, textvariable = mealThreeString)
mealFourKeyword = Entry(root, textvariable = mealFourString)
mealFiveKeyword = Entry(root, textvariable = mealFiveString)
mealSixKeyword = Entry(root, textvariable = mealSixString)
mealLabel = Label(root,text = "meals")
mealLabel.config(font=("Courier", 30))
mealLabel.pack()
mealLone = Label(root,text = "meal one")
mealLtwo = Label(root,text = "meal two")
mealLthree = Label(root,text = "meal three")
mealLfour = Label(root,text = "meal four")
mealLfive = Label(root,text = "meal five")
mealLsix = Label(root,text = "meal six")
caloriesLabel = Label(root,text = "calories needed").pack()
calories = Text(root, height = 1, width = 10).pack()
protienLabel= Label(root,text = "protien ratio").pack()
protien = Text(root, height = 1, width = 4).pack()
carbsLabel = Label(root,text = "carbohydrate ratio").pack()
carbs = Text(root, height = 1, width = 4).pack()
fatsLabel = Label(root,text = "fats ratio").pack()
fats = Text(root, height = 1, width = 4).pack()
displayText = Text(root).pack(side = RIGHT)
def GetEntry(x):
formatted = x.get().split()##gets the entry and forms a list
getMeal = CsvLoadSearch(u, formatted)
meal = OptionMenu(root, '', *getMeal).pack()
mealOneButton = Button(root, text = "query database", command = GetEntry(mealOneString))
mealTwoButton = Button(root, text = "query database", command = GetEntry(mealTwoString))
mealThreeButton = Button(root, text = "query database", command = GetEntry(mealThreeString))
mealFourButton = Button(root, text = "query database", command = GetEntry(mealFourString))
mealFiveButton = Button(root, text = "query database", command = GetEntry(mealFiveString))
mealSixButton = Button(root, text = "query database", command = GetEntry(mealSixString))
mealButtons = [mealOneButton, mealTwoButton, mealThreeButton, mealFourButton, mealFiveButton, mealSixButton]
mealKeywords = [mealOneKeyword, mealTwoKeyword, mealThreeKeyword, mealFourKeyword, mealFiveKeyword, mealSixKeyword]
mealLabels = [mealLone, mealLtwo, mealLthree, mealLfour, mealLfive, mealLsix]
##meals = [mealOne, mealTwo, mealThree, mealFour, mealFive, mealSix]
##packs the drop downs and respective lables
i = 0
while i < len(mealLabels):
mealLabels[i].pack()
mealKeywords[i].pack()
mealButtons[i].pack()
##meal.pack()
i = i + 1
root.mainloop()
throw away lambda function is needed after command when creating the buttons