I create a table but I'm not able to insert values. Database class:
import sqlite3
class Database:
word_list = ["RAFAY", "LION", "PANDA", "TIGER", "DOG", "CAT", "RABBIT", "MOUSE", "PENGUIN"]
def __init__(self, db):
self.con = sqlite3.connect(db)
self.cur = self.con.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS DICTIONARY (ID INTEGER PRIMARY KEY, WORD TEXT NOT NULL)")
self.con.commit()
def add_valid_guessing_word(self):
for word in self.word_list:
self.insert_valid_guessing_word(word)
# Insert Function
def insert_valid_guessing_word(self, guessing_word):
cursor = self.con.cursor()
cursor.execute("INSERT INTO DICTIONARY VALUES (NULL,?)", (guessing_word,))
print("Inserted Data")
self.con.commit()
# Get a Record in DB
def get_valid_guessing_word(self, id):
cursor = self.con.cursor()
cursor.execute("SELECT * FROM DICTIONARY WHERE id=?", (id,))
valid_word = self.cur.fetchone()
print(valid_word)
return valid_word
Main code:
from tkinter import *
from tkinter import messagebox
from string import ascii_uppercase
import random
import sqlite3
from sqdb import Database
window = Tk()
window.title("Hangman")
db = Database("Goiyala.db")
photos = [PhotoImage(file="images/hang0.png"), PhotoImage(file="images/hang1.png"), PhotoImage(file="images/hang2.png"),
PhotoImage(file="images/hang3.png"),
PhotoImage(file="images/hang4.png"), PhotoImage(file="images/hang5.png"), PhotoImage(file="images/hang6.png"),
PhotoImage(file="images/hang7.png"),
PhotoImage(file="images/hang8.png"), PhotoImage(file="images/hang9.png"),
PhotoImage(file="images/hang10.png"), PhotoImage(file="images/hang11.png")]
def newGame():
messagebox.showinfo("Welcome to Hangman","By Roman & Ricario")
global the_word_withSpaces
global numberOfGuesses
global the_word
numberOfGuesses = 0
imgLabel.config(image=photos[0])
value = db.get_valid_guessing_word(random.randint(1, 7))
the_word = str(value[-1])
print(the_word)
the_word_withSpaces = " ".join(the_word)
lblWord.set(" ".join("_" * len(the_word)))
def guess(letter):
global numberOfGuesses
if numberOfGuesses < 11:
txt = list(the_word_withSpaces)
guessed = list(lblWord.get())
if the_word_withSpaces.count(letter) > 0:
for c in range(len(txt)):
if txt[c] == letter:
guessed[c] = letter
lblWord.set("".join(guessed))
if lblWord.get() == the_word_withSpaces:
messagebox.showinfo("Hangman", "You Guessed it")
newGame()
else:
numberOfGuesses += 1
imgLabel.config(image=photos[numberOfGuesses])
if numberOfGuesses == 11:
toast_message = "Game Over! " \
"The Correct answer is {}".format(the_word)
messagebox.showwarning("Hangman", toast_message)
imgLabel = Label(window)
imgLabel.grid(row=0, column=0, columnspan=3, padx=10, pady=40)
imgLabel.config(image=photos[0])
lblWord = StringVar()
Label(window, textvariable=lblWord, font="Consolas 24 bold").grid(row=0, column=3, columnspan=6, padx=10)
n = 0
for c in ascii_uppercase:
Button(window, text=c, command=lambda c=c: guess(c), font="Helvetica 18", width=4).grid(row=1 + n // 9, column=n % 9)
n += 1
Button(window, text="new\nGame", command=lambda: newGame(), font="Helvetica 10 bold").grid(row=3, column=8,
sticky="NSWE")
newGame()
window.mainloop()
Error :
Traceback (most recent call last):
File "C:\Users\Rufez\PycharmProjects\HangmanRicarioRoman2\game.py", line 128, in <module>
hangman = Game(touch.get_valid_word_to_be_execute())
File "C:\Users\Rufez\PycharmProjects\HangmanRicarioRoman2\game.py", line 41, in get_valid_word_to_be_execute
the_word = str(value[-1])
TypeError: 'NoneType' object is not subscriptable
You can't re-use the cursor.
Declare a local cursor each time:
# Get a Record in DB
def get_valid_guessing_word(self, id):
cursor = self.con.cursor() # <<-- HERE new cursor
cursor.execute("SELECT * FROM DICTIONARY WHERE id=?", (id,))
valid_word = cursor.fetchone()
print(valid_word)
return valid_word
As #kuro has pointed out in multiple comments, at no time does the Database.add_valid_guessing_word() function get called in the code. So the table is empty, so the call to db.get_valid_guessing_word(random.randint(1, 7)) returns None. This is not a list-type, hence the error.
Modify your code to put the Animals into the database:
window.title("Hangman")
db = Database("Goiyala.db")
db.add_valid_guessing_word() # <<-- HERE Populate the database
But this will continually add the words, so perhaps check to see if it's not empty first, something like:
window.title("Hangman")
db = Database("Goiyala.db")
if ( db.get_valid_guessing_word( 0 ) == None ):
db.add_valid_guessing_word() # <<-- HERE Populate IFF empty
Then you can also do a debug-dump of the database:
class Database:
# ...
def dumpAnimals( self ):
""" Debug function to dump the Animal Dictionary Table """
cursor = self.con.cursor()
cursor.execute( "SELECT id, word FROM Dictionary ORDER BY word" )
for row in cursor.fetchall():
if ( row == None ):
print( "Dictionary Table is empty" )
break
else:
id_num, word = row
print( "id=%3d, word=[%s]" % ( id_num, word ) )
Using this like:
window.title("Hangman")
db = Database("Goiyala.db")
if ( db.get_valid_guessing_word( 0 ) == None ):
db.add_valid_guessing_word() # <<-- HERE Populate IFF empty
db.dumpAnimals() # <<-- HERE Check we have data
Related
Here is the code of my application
problem
I have used tkinter Entry() method in for loop in ShowOpeanFile() function and I have make One global list variable where I stored the return value of Entry() but when I enter value in that Entry field it effect on all Entry. But I don't want that.
#importing Required library
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
import pandas as pd
from functools import reduce
#Global Variables to Store FilePath That OPEAN
Opean_file_path = []
#Making gloabl datagram object store variable
datgramoffileVariable = []
datagram_list = []
finaldatagram_list = []
#get Filename and qauntity
def getvalue(i):
if Opean_file_path[i][2].get().isnumeric():
return Opean_file_path[i][1],Opean_file_path[i][2].get(),Opean_file_path[i][0]
else:
return -1
#variable making function for file that map each open file during converxlsx function
def variablemaking(size):
temp = []
for number in range(size):
temp.append(str(number))
temp = (list(set(temp)))
datgramoffileVariable.clear()
for i in range(len(temp)):
datgramoffileVariable.append(temp[i])
#conevrting all file to dataGram using pandas library
def Converxlsx():
#makingVariable functioncall
variablemaking(len(Opean_file_path))
#Now variable Making function Done
#Go for the convert datagram to file
for i in range(len(datgramoffileVariable)):
datgramoffileVariable[i] = pd.DataFrame(pd.read_excel(Opean_file_path[i][0]))
for i in range(len(datgramoffileVariable)):
print(datgramoffileVariable[i])
#subpart of Compute function find in list return filepath
def find(target):
for i in range(len(Opean_file_path)):
if(Opean_file_path[i][1] == target):
return Opean_file_path[i][0]
return -1
def findindex(tar):
for i in range(len(Opean_file_path)):
print(Opean_file_path[i][0])
if(Opean_file_path[i][0] == tar):
return i
#ComputeFile function
def compute():
for i in range(len(Opean_file_path)):
v = getvalue(i)
if v == -1:
pass
else:
answerOffind = v[0]
if( answerOffind == -1):
if(label_for_error.cget('text') == "enter right file name"):
label_for_error.config(text="")
else:
label_for_error.config(text="enter right file name", fg='red')
else:
label_for_error.config(text="")
if(len(v[1]) == 0 or v[1].isalpha() or v[1] == ' '):
label_for_error.config(text="enter right Qauntity", fg='red')
pass
else:
if v[1].isnumeric():
if(label_for_error.cget('text') == "enter right Qauntity"):
label_for_error.config(text='')
indexofmaniuplation = findindex(v[2])
print(indexofmaniuplation)
datgramoffileVariable[indexofmaniuplation].qauntity = datgramoffileVariable[indexofmaniuplation].qauntity * int(v[1])
# opeanfile function
def ShowOpeanFile():
col = 0
ro = 0
for i in range(len(Opean_file_path)):
ro = ro + 1
for j in range(len(Opean_file_path[i])):
if j > 1:
Opean_file_path[i][j] = tk.Entry(window,width=20,textvariable=1)
Opean_file_path[i][j].grid(row=ro,column=col)
else:
e = tk.Entry(window, width=20, fg='blue')
e.grid(row=ro,column=col)
e.insert(tk.END,Opean_file_path[i][j])
col = col + 1
col = col - 2
for i in range(len(Opean_file_path)):
for j in range(len(Opean_file_path[i])):
print(Opean_file_path[i][j])
#browsefile function
def browseFiles():
#opeanFile only allow Excel file
'''
askopenfile return file path of selected file
it return type is String
'''
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = [("Excel file","*.xlsx"),("Excel file", "*.xls")]
)
#After getting filepath storing into Opean_file_path list
if(filename in Opean_file_path):
pass
else:
tmp = []
tmp.append(filename)
f=filename.split('/')
tmp.append(f[-1])
tmp.append('qauntitybox')
Opean_file_path.append(tmp)
print(tmp)
Converxlsx()
ShowOpeanFile()
# print(Opean_file_path)
#making final CSV File function.
def csv_making():
datagram_list.clear()
finaldatagram_list.clear()
#convert dataframe into list
for i in range(len(datgramoffileVariable)):
datagram_list.extend(datgramoffileVariable[i].values.tolist())
#find repted element and compute all at one single
repted_element = []
datagram_index_to_be_removed=[]
for i in range(len(datagram_list)):
temp_id = datagram_list[i][0]
temp_Qauntity = datagram_list[i][1]
for j in range(i+1,len(datagram_list)):
if datagram_list[j][0] == temp_id:
temp_Qauntity = temp_Qauntity + datagram_list[j][1]
datagram_index_to_be_removed.append(j)
datagram_index_to_be_removed.append(i)
if [temp_id,temp_Qauntity] not in repted_element and datagram_list[j][0] == temp_id:
repted_element.append([temp_id,temp_Qauntity])
datagram_index_to_be_removed = list(tuple(datagram_index_to_be_removed))
#remove repeted element
datagram_index_to_be_removed.sort()
for i in range(len(datagram_list)):
if i in datagram_index_to_be_removed:
pass
else:
finaldatagram_list.append(datagram_list[i])
#add repted_element
for i in repted_element:
finaldatagram_list.append(i)
#print final data
# print(finaldatagram_list)
#convert final list to csv
id = []
qauntityto = []
for i in range(len(finaldatagram_list)):
id.append(finaldatagram_list[i][0])
qauntityto.append(finaldatagram_list[i][1])
dict = {'id':id,'qauntity':qauntityto}
df = pd.DataFrame(data=dict)
pathofnewfile = df.to_csv('/home/vegg/Desktop/out.csv',index=False)
print(pathofnewfile)
label_for_error.config(text='file save at /home/vegg/Desktop/out.csv',fg='blue')
#UI
window = tk.Tk()
scrollbar = tk.Scrollbar()
frame = tk.Frame(window)
window.geometry("750x400")
label_for_qautity = tk.Label(window ,text="Enter the Qauntity",
width=50,height=3)
label_for_qautity.grid(column=2,row=0)
# Qauntity = tk.Entry()
# Qauntity.grid(column=2,row=1)
label_for_fileNamepath = tk.Label(window ,text="File Name path",
width=20,height=3)
label_for_fileNamepath.grid(column=0,row=0)
label_for_fileName = tk.Label(window ,text="File Name",
width=20,height=3)
label_for_fileName.grid(column=1,row=0)
label_for_error = tk.Label(window ,text="",
width=20,height=3)
label_for_error.grid(column=4,row=3)
button_explore = tk.Button(window,
text = "Browse Files here",
command=lambda :[browseFiles()] )
button_Compute = tk.Button(window,
text = "Compute File Data",
command=lambda :[compute()] )
button_CSV = tk.Button(window,
text = "Create CSV Here",
command=lambda :[csv_making()] )
button_explore.grid(column=4,row=0)
button_Compute.grid(column=4,row=1)
button_CSV.grid(column=4, row=2)
window.mainloop()
Image
I want to add different value for entry not same value effect to all entry.
I have a piece of code in python which generates buttons dependant on the rooms in a list in my database. I would like the code to return the room name on the button that I have selected and use it to store data in my database for that button
class buttongen():
def __init__(self,i,row):
self.i = i
self.row = row
self.roomname = self.row[0]
roomclicked = self.roomname
self.btn = Button(screen13, text=self.roomname, command=lambda :print("self.roomname"))
self.btn.grid(row=i, column=0)
Here is the class for each button and below is the code which gets the list of room names and prints them out as buttons. Is there a way I can store the text and use either .cget() or get() to return the name of the room
def search():
global screen13
global btn
global roomclicked
screen13 = Tk()
screen13.geometry("300x250")
screen13.title("Rooms")
sitename3_info = sitename.get().strip()
if sitename3_info:
cursor = cnn.cursor()
# combine the two SQL statements into one
sql = ("SELECT roomname FROM rooms, Sites "
"WHERE rooms.siteID_fk2 = Sites.siteID AND siteName = %s")
cursor.execute(sql, [sitename3_info])
rooms = cursor.fetchall()
# remove previous result (assume screen13 contains only result)
for w in screen13.winfo_children():
w.destroy()
if rooms:
for i, row in enumerate(rooms):
buttongen(i, row)
roomname = row[0]
roomclicked = roomname
btn = Button(screen13, text=roomname, command=lambda room=roomname: action(room))
btn.grid(row=i, column=0)
else:
Label(screen13, text="No room found").grid()
EDIT
this is the block to create the audit
def createaudit():
sitename2_info = sitename.get()
print(sitename2_info)
name2_info = name2.get()
print(name2_info)
name3_info = name3.get()
print(name3_info)
# Sql code for writing the data that was written in the regsitering page.
cursor = cnn.cursor()
# the site query matches the inputted username with the corresponding userID and inserts the userID into userID_fk
siteIDQuery = "SELECT siteID FROM Sites WHERE siteName = %s"
cursor.execute(siteIDQuery, [sitename2_info])
siteID_fetch = cursor.fetchall()
print(siteID_fetch[0][0])
sitequery = "INSERT INTO `audit`(`siteID_fk`, `auditor1`, `auditor2`) VALUES (%s, %s, %s)"
sitequery_vals = (siteID_fetch[0][0], name2_info, name3_info)
cursor.execute(sitequery, sitequery_vals)
# prints how many rows were inserted to make sure values are put into the database
print(cursor.rowcount)
cnn.commit()
if siteID_fetch:
for i in siteID_fetch:
search()
break
else:
failed2()
this is the block to print out the rooms within the site that's going to be audited
def search():
screen13 = Tk()
screen13.geometry("300x250")
screen13.title("Rooms")
sitename3_info = sitename.get().strip()
if sitename3_info:
cursor = cnn.cursor()
# combine the two SQL statements into one
sql = ("SELECT roomname FROM rooms, Sites "
"WHERE rooms.siteID_fk2 = Sites.siteID AND siteName = %s")
cursor.execute(sql, [sitename3_info])
rooms = cursor.fetchall()
# remove previous result (assume screen13 contains only result)
for w in screen13.winfo_children():
w.destroy()
if rooms:
for i, row in enumerate(rooms):
roomname = row[0]
btn = Button(screen13, text=roomname, command=lambda room=roomname: action(room))
btn.grid(row=i, column=0)
else:
Label(screen13, text="No room found").grid()
This is the block of code where I wish to answer questions for the room and store the answers in my database for it
def action(roomname):
global screen15
screen15 = Tk()
screen15.geometry("300x250")
screen15.title("Rooms")
global q1
global q2
global q3
q1 = StringVar()
q2 = StringVar()
q3 = StringVar()
Label(screen15, text = "Please enter details below", bg = "LightSkyBlue1", width = "300", height = "2").pack()
Label(screen15, text = "").pack()
Label(screen15, text = "01. Commodes CLEANING").pack()
q1_entry = Entry(screen15, textvariable = q1)
q1_entry.pack()
Label(screen15, text = "02. commodes NURSING").pack()
q2_entry = Entry(screen15, textvariable = q2)
q2_entry.pack()
Label(screen15, text = "03. Bathroom Hoists CLEANING").pack()
q3_entry = Entry(screen15, textvariable = q3)
q3_entry.pack()
Button(screen15, text = "Create an Audit", width = "12", height = "1", command = storescore).pack()
def storescore():
roomname2_info = buttongen(self.roomname).cget()
print(roomname2_info)
sitenameInfo = sitename.get()
# sql to store answer values
cursor = cnn.cursor()
siteID_fetch4 = "SELECT siteID FROM Sites WHERE siteName = %s"
cursor.execute(siteID_fetch4, [sitenameInfo])
siteID_fetch4 = cursor.fetchall()
print(siteID_fetch4[0][0])
roomsFID = "SELECT roomID FROM rooms WHERE siteID_fk2 = %s AND roomname = %s"
cursor.execute(roomsFID, [(siteID_fetch4[0][0]), (roomname2_info)])
roomsFID = cursor.fetchall()
print(roomsFID[0][0])
Code below will do the trick perfectly (just adjust it to your needs):
import tkinter as tk
def safe_to_sql(number):
print("Saving room {} into SQL ...".format(number))
#Save whatever you want
def addButton(window, buttons, room):
new_button = tk.Button(window, text = "Room:" + room, command = lambda: safe_to_sql(room))
new_button.pack()
buttons.append(new_button)
my_buttons = []
rooms = ["Room 1", "Super room 2", "Ever better one"]
window = tk.Tk()
for room in rooms:
addButton(window, my_buttons, room)
window.mainloop()
We are creating dynamical buttons.
To each button we connect this lambda function: command = lambda: safe_to_sql(room).
I'm using tkinter in python and I'm trying to add data into database but with a column id which is auto_increment, I cannot leave the value empty for column id, it returns error row count doesn't match column count at row 1. Is there a solution to this?
def database():
nme = name.get()
p_h = ph.get()
eid = e_id.get()
ema_id = em_id.get()
nat = nation.get()
emer = emerg.get()
gend = g.get()
bloo = b.get()
covi = co.get()
dat = cal.selection_get()
if nme=="" or p_h=="" or eid=="" or ema_id=="" or nat=="" or emer=="" or gend=="" or bloo=="" or covi=="" or dat=="":
messagebox.showinfo('Fill all','All fields are necessary')
else:
con = mysql.connect(host='db4free.net', user='nihaalnz', password='*****', database='nihaalnztrying')
c = con.cursor()
c.execute("Insert into PATIENTS VALUES ('"+nme+"','"+p_h+"','"+eid+"','"+ema_id+"','"+gend+"','"+str(dat)+"','"+nat+"','"+str(bloo)+"','"+str(covi)+"','"+emer+"','""')")
c.execute('commit')
con.close()
messagebox.showinfo('Success','All values have been entered to the database')
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e6.delete(0, END)
I have a table that has only 1 row, I only need to update the data in the first row. I need to preview the data at the startup like Total Wealth :- 2000 Cash :- 0 Savings :- 2000. But it previews like shown below. enter image description here So please give me a solution for this.
from tkinter import *
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="postgres",
host="localhost",
port="5432",
database="money_db")
cursor = connection.cursor()
query_cash = "select cash from main where index = 1;"
query_savings = "select savings from main where index = 1;"
cursor.execute(query_cash)
cash = cursor.fetchall()
cursor.execute(query_savings)
savings = cursor.fetchall()
t_w = (cash + savings)
cursor.execute("commit;")
if (connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
root = Tk()
root.geometry("900x500")
root.resizable(width=False, height=False)
t_w_lbl = Label(text="Total Wealth = " + str(t_w), font=("Calibry", 14), bg="white")
t_w_lbl.place(rely=0.04, relx=0.1)
cash_lbl = Label(text="Cash = " + str(cash), font=("Calibry", 14), bg="white")
cash_lbl.place(rely=0.04, relx=0.45)
photo = PhotoImage(file = "exchange.png")
exchange_btn = Button(image = photo, command = lambda: exchange())
exchange_btn.place(relx = 0.64, rely = 0.03, height = 35, width = 50)
savings_lbl = Label(text="Savings = " + str(savings), font=("Calibry", 14), bg="white")
savings_lbl.place(rely=0.04, relx=0.8)`
You should use the fetchone method instead and unpack the returning tuple (note the added comma).
Change:
cash = cursor.fetchall()
...
savings = cursor.fetchall()
to:
cash, = cursor.fetchone()
...
savings, = cursor.fetchone()
I've some code to input data into list, how can I import data in my list into database?
import psycopg2
import random
import string
import time
conn = psycopg2.connect(host="localhost",database="postgres", user="postgres", password="potatona1")
cursor = conn.cursor()
FullChar = 'CEFLMPRTVWXYK0123456789#'
total = 4
count = 10
count = int(count)
for i in range(1000):
for x in range(total):
unique_code = ''.join(random.sample(FullChar, count - 1)) + '#'
unique_code = ''.join(random.sample(unique_code, len(unique_code)))
list(unique_code)
postgres_insert_query = """ INSERT INTO employees (id_employee, name) VALUES (%s,%s)"""
record_to_insert = (1, unique_code)
cursor.execute(postgres_insert_query, record_to_insert)
conn.commit()
count = cursor.rowcount
print (count, "Record inserted successfully into mobile table")
I want import 1000 data to postgresql with python.
i just trying this, and it works
conn = psycopg2.connect(host="192.168.13.10",database="postgres", port="5432", user="postgres", password="potatona1")
cursor = conn.cursor()
FullChar = 'CEFLMPRTVWXYK0123456789'
total = 1000
count = 10
count = int(count)
entries = []
bcd = ""
flg = ""
rll = ""
def inputDatabase(data):
postgres_insert_query = """INSERT INTO unique_code(unique_code, barcode, flag, roll) VALUES (%s,%s,%s,%s)"""
cursor.executemany(postgres_insert_query, data)
conn.commit()
for i in range(5):
for x in range(total): # banyaknya code yang di print
unique_code = ''.join(random.sample(FullChar, count - 1))
unique_code = ''.join(random.sample(unique_code, len(unique_code)))
entry = (unique_code, bcd, flg, rll)
entries.append(entry)
inputDatabase(entries)
print(i)
count = cursor.rowcount
print (count, "Record inserted successfully into mobile table")